If I understand the results correctly, you want a cumulative sum of DLY_Cnt
. You can do this quite readily in SQL Server 2012:
SELECT PersonID, Mth, Yr, COUNT(*) as DLY_Cnt,
RANK() OVER (PARTITION BY PersonID, Mth ORDER BY Yr DESC) as YrRnk,
SUM(COUNT(*)) (PARTITION BY PersonId, Mth ORDER BY Yr) as DPY_Cnt
FROM #BkgSummary
GROUP BY PersonID, Mth, Yr;
You can do something similar using correlated subqueries in earlier versions:
with t as (
SELECT PersonID, Mth, Yr, COUNT(*) as DLY_Cnt,
RANK() OVER (PARTITION BY PersonID, Mth ORDER BY Yr DESC) as YrRnk
FROM #BkgSummary
GROUP BY PersonID, Mth, Yr
)
select t.*,
(select sum(DLY_CNT)
from t t2
where t.PersonID = t2.PersonId and
t.Yr = t2.Yr and
t.Mth >= t2.Mth
) as DPY_Cnt
from t;