我的交易表如下所示。我需要创建一个存储过程来计算StockLevel
列。
日期是连续的(总是1天差距),公式为:
StockLevel = yesterdayStockLevel + AIn - AOut
示例数据:
Date | ArticleId | AOut | AIn | StockLevel
Aug 1 1 1 10 10 - 1 = 9
Aug 2 1 2 0 9 - 2 = 7
Aug 3 1 1 0 7 - 1 = 6
Aug 4 1 2 0 6 - 2 = 4
Aug 5 1 3 5 4 - 3 + 5 = 6
Aug 6 1 0 0 6 - 0 = 6
我更喜欢在SQL上运行它(如果可能的话)而不是使用游标(如果可能的话)。
谢谢!
答案 0 :(得分:0)
试试这个:
Select Date, ArticleID, AOut, AIn, AInSum-AOutSum as StockLevel
From (
Select *,
sum(AOut)over (Partition by ArticleId Order by Date) AOutSum,
sum(AIn)over (Partition by ArticleId Order by Date) AInSum
From yourTabble
) X