Esto se puede hacer usando una solución basada en conjuntos:
1. Calcule el total acumulado normal (llámelo RT)
2.Calcule el mínimo de ejecución de RT (llámelo MN)
Cuando MN es negativo, -MN es la cantidad total que tuvo que reponer hasta el momento. Sea replenish_rt -MN cuando MN es negativo. Entonces, el nuevo total acumulado (llámelo new_rt) es rt + replenish_rt. Y si necesita devolver la cantidad de reabastecimiento actual necesaria, reste el replenish_rt anterior (usando LAG) del actual.
Aquí está la consulta de solución completa:
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);
Saludos, Itzik