SQL Temp table 执行滚动计算的数组
SQL Temp table Array to perfrom rolling caluclations
我希望使用某种 SQL 数组从特定行 (QTYOnHand
) 中减去值,每次都减少该行值并将其投入其他行的滚动计算.我一直在考虑某种 Self Join/Temp Table 解决方案,但不确定如何制定。此外,所有结果将按下面的 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 对于 Item_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
尝试以下操作:
;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
请找到数据库<>fiddle here.
我希望使用某种 SQL 数组从特定行 (QTYOnHand
) 中减去值,每次都减少该行值并将其投入其他行的滚动计算.我一直在考虑某种 Self Join/Temp Table 解决方案,但不确定如何制定。此外,所有结果将按下面的 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 对于 Item_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
尝试以下操作:
;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
请找到数据库<>fiddle here.