从一行中获取先前的计算值,并在同一列的下一行中更新该值,然后减去该值。Microsoft SQL Server

时间:2018-10-08 11:34:55

标签: sql sql-server

下面是我在SQL Server中的现有表。我只想为每个ChildID组找到GAP,即ClosingStock-需求

Existing Table:

ParentID    ChildID   Demand    ClosingStock  BasicFinishDate
2537        3064        8           161         9/18/2018
5407        6238        25          161         9/28/2018
5056        6238        30          161         9/28/2018
5056        6238        10          161         10/3/2018
5407        6238        45          161         10/5/2018
5498        8462        3           161         9/10/2018
5498        8462        9           161         9/27/2018
5498        8462        144         161         10/3/2018
5498        8462        1           161         10/4/2018


Expected Result:

ParentID   ChildID   Demand   ClosingStock  Gap        BasicFinishDate
2537        3064        8           161     153         9/18/2018
5407        6238        25          161     136         9/28/2018
5056        6238        30          136     106         9/28/2018
5056        6238        10          106     96          10/3/2018
5407        6238        45          96      51          10/5/2018
5498        8462        3           161     158         9/10/2018
5498        8462        9           158     149         9/27/2018
5498        8462        144         149     5           10/3/2018
5498        8462        1           5       4           10/4/2018

差距计算为期末库存-(减去)需求。

如果

ClosingStock列具有相似的ChildID,也必须使用以前的Gap值进行更新

。谢谢。

1 个答案:

答案 0 :(得分:-1)

希望以下查询会为您提供帮助。

SELECt 
        ParentID
        ,ChildID
        ,Demand
        ,ClosingStock
        ,ClosingStock-Demand as gap
        ,BasicFinishDate
FROM 
(
SELECT 
        ParentID 
        ,ChildID
        ,Demand 
        ,ClosingStock - (CASE WHEN Demand=DemandTotal THEN 0 ELSE LAG(DemandTotal)OVER(PARTITION by ChildID Order by BasicFinishDate asc, PArentId desc ) END)  as ClosingStock
        ,BasicFinishDate
FROM 
(
SELECT  
        ParentID 
        ,ChildID
        ,Demand 
        ,SUM(Demand) OVER (partition by ChildID ORDER BY BasicFinishDate asc, PArentId desc ROWS UNBOUNDED PRECEDING) AS DemandTotal 
        ,ClosingStock
        ,BasicFinishDate
FROM #test
)R
)Q