如何编写SQL LAG查询来获取运行总计的最大值?

问题描述 投票:0回答:1

例如如果为运行总计求和的值有时为负数,则运行总计可能会下降。但对于每一行,我还希望达到该点的最大运行总数...

如何对此代码进行增强?

select ItemId, DateId, TargetRunningStock, 
       sum(TargetRunningStock) over (partition by itemid order by dateid)
from WarehouseData
sql sum aggregate lag
1个回答
0
投票

您可以添加另一个级别:

select ItemId, DateId, TargetRunningStock, RunTot,
       Max(RunTot) over (partition by itemid order by dateid) as MaxRunTot
from (
  select ItemId, DateId, TargetRunningStock, 
       sum(TargetRunningStock) over (partition by itemid order by dateid) as RunTot
  from WarehouseData
) Step1
© www.soinside.com 2019 - 2024. All rights reserved.