Isso pode ser feito usando uma solução baseada em conjunto:
1. Calcule o total de corrida normal (chame-o de RT)
2. Calcule o mínimo de RT (chame-o de MN)
Quando MN é negativo, -MN é a quantidade total que você teve que reabastecer até o momento. Seja replace_rt -MN quando MN for negativo. Portanto, o novo total em execução (chame-o de new_rt) é rt + reabastecer_rt. E se você precisar retornar a quantidade atual de reabastecimento necessária, subtraia o reabastecimento anterior (usando LAG) do atual.
Aqui está a consulta de solução 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);
Saúde, Itzik