SQL Server 2016 - 计算剩余库存数量

2023-11-30

我有一个这样的表:

Table Layout

正如您所看到的,我有一个名为remaining_stock 的列,该列对于每个项目的第一行是正确的,但对于后续行则不正确。第一行很简单,因为您可以简单地从initial_stock 中减去订单数量。

我想要实现的是获得一个剩余库存列,如下所示:

Desired Result

我虽然使用 row_number 然后使用行号连接回同一个表..但这也不太有效。有人可以指出我正确的方向吗?

select 1 as line, 123 as item, 5 as order_quantity,10 as intial_stock
union all
select 2 as line, 123 as item, 3 as order_quantity,10 as intial_stock
union all
select 3 as line, 123 as item, 1 as order_quantity,10 as intial_stock
union all
select 4 as line, 234 as item, 5 as order_quantity,15 as intial_stock
union all
select 5 as line, 234 as item, 3 as order_quantity,15 as intial_stock
union all
select 6 as line, 234 as item, 1 as order_quantity,15 as intial_stock

小题大做使用窗口函数Sum()过来

Example

Select * 
      ,Remaining_Stock = intial_stock - sum(Order_Quantity) over (Partition By Item Order by Line)
 from YourTable

Returns

line    item    order_quantity  intial_stock    Remaining_Stock
1       123     5               10              5
2       123     3               10              2
3       123     1               10              1
4       234     5               15              10
5       234     3               15              7
6       234     1               15              6
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SQL Server 2016 - 计算剩余库存数量 的相关文章

随机推荐