A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Try this query:
;
with Y
as
(
select m
from (values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)) as Y(m)
),
X as
(
select Id, MAX(ReportMonth) as mm
from #Temp
group by Id
)
select X.Id,
Y.m as ReportMonth,
(Y.m - 1) / 3 + 1 as ReportQuarter,
isnull(t.PaymentAmount, $0) as PaymentAmount,
sum(t.PaymentAmount) over (partition by X.Id order by Y.m rows between unbounded preceding and current row) as CummulativeAmount
from Y
cross apply X
left join #Temp as t on t.Id = X.Id and t.ReportMonth = Y.m
where Y.m <= X.mm
order by Id, ReportMonth