从一行中获取上一个计算值,并在下一行的同一列中更新该值,然后用该值减去。。Microsoft SQL Server
下面是我在SQL server中的现有表。我只想找出每个儿童群体的差距,即关闭股票需求从一行中获取上一个计算值,并在下一行的同一列中更新该值,然后用该值减去。。Microsoft SQL Server,sql,sql-server,Sql,Sql Server,下面是我在SQL server中的现有表。我只想找出每个儿童群体的差距,即关闭股票需求 Existing Table: ParentID ChildID Demand ClosingStock BasicFinishDate 2537 3064 8 161 9/18/2018 5407 6238 25 161 9/28/2018 5056
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,则该列还必须使用以前的间隙值进行更新
。提前感谢。希望下面的查询能对您有所帮助
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
您是如何得到第三行中的值136和106的?也就是说,间隙136和106属于ChildID组6238。161-25是136,136-30是106。。。Closing Stock-Demand is GAPClosing Stock列必须更新,对于缺口计算,它应采用更新的期末库存值。请在问题中解释此逻辑。如果人们不必阅读所有的评论来获得他们需要的信息,你可能会得到更多的答案。要做到这一点,你需要确保你的表格总是正确排序。我们可以使用哪个列对此进行排序?