试图让跑步总数上班

时间:2018-06-22 16:50:57

标签: sql sql-server

我有一个查询,非常适合将ElapsedTime组合在一起,当NonProductive = 1时,该时间被视为非生产时间。但是,我一直在尝试使运行总计发挥作用。这是每天按ReportNo总计的主要查询:

Select SUM(CASE
           When NonProductive = 1 Then ElapsedTime
           Else 0
           End) 
            From DailyOperations
           Where (DailyOperations.WellID = 'ZCQ-5') AND (DailyOperations.JobID = 'Original')  and (ReportNo = 9)

ReportNo = 9是第一个具有非生产时间的Reportno,为4。下一个是ReportNo =14。它具有5.5个小时的非生产时间。因此,当我运行ReportNo 14时,我希望看到的总数为9.5,仅此而已。以下是我用于运行总计的查询,但它列出了所有非生产时间。因此,我不仅获得了ReportNo 14的9.5,而且还获得了报告中每个非生产时间实例的运行总计:

SELECT (ElapsedTime),(Reportno),NonProductive,
SUM(ElapsedTime) OVER (PARTITION BY NonProductive ORDER BY REPORTNO ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS RUNNINGTOTAL
FROM            dbo.DailyOperations
WHERE  (NonProductive IN(1)) and  (WellID = 'ZCQ-5') AND (JobID = 'Original')  

Group by ReportNo,ElapsedTime,NonProductive

Order by ReportNo

这给了我

ReportNo      RUNNINGTOTAL
     9               4
     14              6
     14             9.5

我想要的是:

ReportNo      RUNNINGTOTAL
     9               4
     14              9.5

1 个答案:

答案 0 :(得分:0)

我想你想要

SELECT Reportno,NonProductive,
       SUM(SUM(ElapsedTime)) OVER (PARTITION BY NonProductive ORDER BY REPORTNO) AS RUNNINGTOTAL
FROM dbo.DailyOperations o
WHERE NonProductive IN (1) and WellID = 'ZCQ-5' AND JobID = 'Original') 
GROUP BY ReportNo
ORDER BY ReportNo;

注意:

  • GROUP BY定义结果集中所需的每一行。因此,您只需要ReportNo
  • 将窗口函数和聚合函数组合在一起时,有时会遇到外观奇怪的构造,例如SUM(SUM())
  • 不需要窗口子句。使用ORDER BY时,您拥有的基本上是默认设置(实际上,默认设置是RANGE BETWEEN,但是ReportId是唯一的,因此两者是等效的。)