在相同表格中求前一行数值之和

huangapple go评论103阅读模式
英文:

Sum previous row values in same table

问题

  1. | ItemID | Qty | 库存余量(更新为此列的结果)
  2. | -------- | -------- |---------------
  3. | 1000 | 1 | 1
  4. | 1000 | 5 | 6(前一行的数量之和加上当前行的数量)
  5. | 1000 | 2 | 8(前一行的数量之和加上当前行的数量)
  6. | 1000 | 1 | 9(前一行的数量之和加上当前行的数量)
英文:

I try to sum value in pervious rows, I want to sum the pervious quantity "Stock on hand" and put the result in each row, example

ItemID Qty Stockon Hand ( the result updated in this column)
1000 1 1
1000 5 6 ( sum qty previous in pervious row plus the qty in the current row)
1000 2 8 ( sum qty previous in pervious row plus the qty in the current row)
1000 1 9 ( sum qty previous in pervious row plus the qty in the current row)

How can I update the column "Stock on hand" by summing the qty in the current row and previous rows?

  1. select ItemID, Qty
  2. , sum(qty) over (order by itemid rows between 1 preceding and 1 preceding) as previous_Qty
  3. from #Stock
  4. order by itemid

答案1

得分: 1

这是一个可行的示例。请注意,我在列名中添加了一个适当的序列ID,但您也可以使用日期列。

您还可以注意到我添加了 partition by ItemID

  1. Declare @YourTable Table ([ID] int,[ItemID] int,[Qty] int)
  2. Insert Into @YourTable Values
  3. (1,1000,1)
  4. ,(2,1000,5)
  5. ,(3,1000,2)
  6. ,(4,1000,1)
  7. Select *
  8. ,OnHand = sum(Qty) over (partition by ItemID order by ID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
  9. from @YourTable

结果

  1. ID ItemID Qty OnHand
  2. 1 1000 1 1
  3. 2 1000 5 6
  4. 3 1000 2 8
  5. 4 1000 1 9
英文:

Here is a working example. Note, I took the liberty of adding an column for a proper sequence... ID, but you could use a date column as well

You may also notice that I added partition by ItemID

  1. Declare @YourTable Table ([ID] int,[ItemID] int,[Qty] int)
  2. Insert Into @YourTable Values
  3. (1,1000,1)
  4. ,(2,1000,5)
  5. ,(3,1000,2)
  6. ,(4,1000,1)
  7. Select *
  8. ,OnHand = sum(Qty) over (partition by ItemID order by ID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
  9. from @YourTable

Results

  1. ID ItemID Qty OnHand
  2. 1 1000 1 1
  3. 2 1000 5 6
  4. 3 1000 2 8
  5. 4 1000 1 9

huangapple
  • 本文由 发表于 2023年1月6日 10:33:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75026383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定