缺少日期的运行总额

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

我有一个这样的数据表:

PeriodYearMonth Reg      PartNo             ComponentRemovals   RunningRemovals
2019 10         G-NHVP   109-0740V01-137    1                    1
2019 11         G-NHVP   109-0740V01-137    1                    2  
2019 12         G-NHVP   109-0740V01-137    1                    3
2020 01         G-NHVP   109-0740V01-137    1                    4
2019 10         OO-NSF   11-13354P          1                    1
2019 09         G-NHVR   11-13354P          2                    2 
2019 10         OY-HMV   11-13354P          1                    1

在最后一列中,我计算了过去7个月每个部件号和每个Reg的去除量的总和。为此,我编写了以下代码:

/****** Find Running Component Removals ******/
SELECT  [PeriodYearMonth]
      ,[Reg]
      ,[PartNo]
      ,[ComponentRemovals]
      ,sum(sum(ComponentRemovals)) over (Partition by [Reg], PartNo Order By PeriodYearMonth, PeriodYearMonth rows between 6 preceding and current row) as RunningRemovals
      ,[ConfirmedFailures]
      , sum(sum(ConfirmedFailures)) over (Partition by [Reg], PartNo Order By PeriodYearMonth, PeriodYearMonth rows between 6 preceding and current row) as RunningFailures

  FROM [RALNHVTST].[dbo].[vtRelRepComponentsRemovalsByPartNo]

  Group by Reg, PartNo, ComponentRemovals, ConfirmedFailures, PeriodYearMonth
  Order by PartNo

但是,由于并非所有月份都包含在PeriodYearMonth列中,因此结果不正确。我已经在网上看到了一些简单案例的解决方案,但是对我来说,棘手的是,我需要为每个PartNo,每个Reg和每个月输入一个条目。

任何帮助将不胜感激。

问候

sql date sum ssms
1个回答
0
投票
在最后一列中,我计算了过去7个月每个部件号和每个Reg的去除量的总和。

删除窗口子句和过滤器:

select [PeriodYearMonth], [Reg], [PartNo], [ComponentRemovals], sum(sum(ComponentRemovals)) over (Partition by [Reg], PartNo Order By PeriodYearMonth, PeriodYearMonth) as RunningRemovals [ConfirmedFailures], sum(sum(ConfirmedFailures)) over (Partition by [Reg], PartNo Order By PeriodYearMonth, PeriodYearMont) as RunningFailures from [RALNHVTST].[dbo].[vtRelRepComponentsRemovalsByPartNo] where PeriodYearMonth >= format(dateadd(month, -7, getdate()), 'yyyy MM') group by Reg, PartNo, ComponentRemovals, ConfirmedFailures, PeriodYearMonth Order by PartNo

© www.soinside.com 2019 - 2024. All rights reserved.