我有一张这样的表:
正如您所看到的,我有一个名为remaining_stock的列对于每个项目的第一行是正确的,但对于后续行没有。第一行是直接的,因为您可以简单地从initial_stock中减去订单数量。
我想要的是获得一个看起来像这样的remaining_stock列:
我虽然使用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
答案 0 :(得分:3)
使用窗口函数Sum()的小问题
示例强>
function BytestoSmallInt(B0, B1: Byte): SmallInt;
var
Number: SmallInt;
pointer : ^SmallInt;
small: array [0 .. 1] of Byte absolute Number;
begin
pointer := @Number;
small[0] := B1;
small[1] := B0;
Result := pointer^;
end;
<强>返回强>
Select *
,Remaining_Stock = intial_stock - sum(Order_Quantity) over (Partition By Item Order by Line)
from YourTable