SQL Server 2016 - Calculating remaining stock quantity

拟墨画扇 提交于 2020-01-04 07:28:08

问题


I have a table like this:

As you can see, I have a column called remaining_stock that is correct for the first line of each item but NOT for the subsequent lines. The first line is straight forward as you can simply subtract the order-quantity from initial_stock..

What I want to achieve is to get a remaining_stock column that looks like this:

I though of using row_number and then joining back to the same table using the row numbers.. but that doesn't quite work either. can someone point me in the right direction please?

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

回答1:


Small matter using the window function Sum() over

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


来源:https://stackoverflow.com/questions/48216733/sql-server-2016-calculating-remaining-stock-quantity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!