I am looking at creating a rolling sum in SQL Server similar to the Excel breakout below. The issue I am unable to work around (after primarily utilizing the lag function) is that I need to start summing the daily extra and the previous rollover. There is an Excel table similar to what I am trying to achieve along with code I have attempted.
select *,
case when lag([daily_extra],1) over (order by [date]) = 0 and [daily_extra] > 0 then
[daily_extra] else
case when lag([daily_extra],1) over (order by [date]) > 0 and [daily_extra] > 0 then
[daily_extra]+lag([daily_extra],1) over (order by [date]) else 0 end end [Rollover]
from
(
select [date],
[tickets_sold] [TICKETS],
[max_tickets] [MAX TICKETS],
case when [tickets_sold]-[max_tickets] > 0 then [tickets_sold]-[max_tickets]
else 0 end [Daily Extra]
from table
) t1
1条答案
按热度按时间du7egjpx1#
As mention in the comment, you need to use recursive cte as your
rollover
value is depends on previous calculated value