यह एक सेट-आधारित समाधान का उपयोग करके किया जा सकता है:
1. सामान्य चलने वाले कुल की गणना करें (इसे RT कहते हैं)
2. चल रहे न्यूनतम RT की गणना करें (इसे MN कहते हैं)
जब MN ऋणात्मक होता है, -MN वह कुल मात्रा होती है जिसकी आपको अब तक पूर्ति करनी होती है। जब MN ऋणात्मक हो, तो फिर से भरना_rt -MN होने दें। तो, नया चल रहा कुल (इसे new_rt कहते हैं) 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);
चीयर्स, इत्ज़िकी