执行滚动计算的sql临时表数组

3xiyfsfu  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(322)

我希望使用某种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列值中减去下一个值。看起来像17-3,然后14-5,然后9-4对于物品id(123):
(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
7gcisfzg

7gcisfzg1#

请尝试以下操作:

;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

请在这里找到小提琴。

相关问题