これは、セットベースのソリューションを使用して実行できます:
1.通常の現在の合計を計算します(RTと呼びます)
2.実行中の最小RTを計算します(MNと呼びます)
MNが負の場合、-MNはこれまでに補充しなければならなかった合計量です。 MNが負の場合、replenish_rtを-MNとします。したがって、新しい現在の合計(new_rtと呼びます)はrt+replenish_rtです。また、必要な現在の補充量を返す必要がある場合は、現在の補充量から以前のreplenish_rt(LAGを使用)を差し引きます。
完全なソリューションクエリは次のとおりです。
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);
乾杯、Itzik