Można to zrobić za pomocą rozwiązania opartego na zestawie:
1.Oblicz normalną bieżącą sumę (nazwij ją RT)
2.Oblicz bieżące minimum RT (nazwij to MN)
Gdy MN jest ujemne, -MN to całkowita ilość, którą musiałeś do tej pory uzupełnić. Niech replenish_rt będzie równe -MN, gdy MN jest ujemne. Tak więc nowa suma bieżąca (nazwijmy ją new_rt) to rt + replenish_rt. A jeśli chcesz zwrócić aktualną potrzebną ilość uzupełnień, odejmij poprzednią wartość replenish_rt (przy użyciu LAG) od bieżącej.
Oto kompletne zapytanie o rozwiązanie:
with c1 as
(
select *,
sum(qty) over(order by tdate rows unbounded preceding) as rt
from tx
),
c2 as
(
select *,
-- when negative, mn is the total qty that had to be
-- replenished until now, inclusive
min(rt) over(order by tdate rows unbounded preceding) as mn_cur
from c1
)
select tdate, qty, rt,
replenish_rt - lag(replenish_rt, 1, 0) over(order by tdate) as replenish,
rt + replenish_rt as new_rt
from c2
cross apply(values(case when mn_cur < 0 then -mn_cur else 0 end)) as a1(replenish_rt);
Pozdrawiam, Itzik