我希望使用某种类型的SQL数组从某一行(QTYOnHand)中减去值,该值每次都会减少该行值,并将其抛到其他行的滚动计算中。我一直在考虑某种自联接/临时表解决方案,但不确定如何制定。另外,所有结果都将由下面的ItemID进行分区。我会感谢你的帮助。
这里有一些数据,如果我做一个简单的逐行减法,我将得到如下结果: 17-3 = 14,17-5 = 12,等等。
(Item_ID) (ItemQty) (QTYOnHand) (QtyOnHand - ItemQty)
123 3 17 14
123 5 17 12
123 4 17 13
456 7 12 5
456 8 12 4
456 2 12 10
456 3 12 9
789 2 6 4
789 2 6 4
789 2 6 4这些是我想要的结果,从新的QTYOnHand-ItemQty列值中减去下一个值。对于Item_ID (123),看起来像是17-3然后14 -5然后9 -4:
(Item_ID) (ItemQty) (QTYOnHand) (QtyOnHand - ItemQty)
123 3 17 14
123 5 17 9
123 4 17 5
456 7 12 5
456 8 12 -3
456 2 12 -5
456 3 12 -8
789 2 6 4
789 2 6 2
789 2 6 0发布于 2020-06-28 06:43:23
尝试以下几点:
;with cte as
(
select *, ROW_NUMBER() over (partition by Item_ID order by Item_ID) rn
from YourTable
)
, cte2 as
(
select Item_ID, ItemQty, QTYOnHand, Case when rn = 1 then QTYOnHand else 0 end - ItemQty as calc, rn
from cte
)
select Item_ID, ItemQty, QTYOnHand, sum(calc) over (partition by Item_ID order by rn) as [QtyOnHand - ItemQty]
from cte2 t1请找到db<>fiddle 这里。
https://stackoverflow.com/questions/62618330
复制相似问题