2016-08-15 91 views
1

我有一个查询,该查询返回给定机器生产运行期间发生的事件的时间戳之间的秒数。总结时间戳之间的经过时间SQL Server

我想获得在该持续时间内机器状态代码分组的时间总量。防爆。运行,计划外停机,计划停机。

我认为这涉及到我知道不允许的聚合的聚合。我相信是有办法做到这一点,虽然

SELECT 
    p1.productionRunId, 
    p1.statusCodeId, 
    DATEDIFF(SECOND, MAX(p2.startTime), p1.startTime) AS seconds 
FROM 
    productionLog p1 
INNER JOIN 
    wincc.dbo.productionLog p2 ON p1.productionRunId = p2.productionRunId 
           AND p2.startTime < p1.startTime 
GROUP BY 
    p1.startTime, p1.productionRunId, p1.statusCodeId 

Here is a picture of my current results with a description of what I would like.

+0

从'group by'中删除'p.startTime'。 –

回答

1

我想你几乎拥有它。您可以使用上面的SELECT查询作为另一个查询的子查询来处理汇总时间段。看看这是不是你要找的东西:

declare @p table (startTime datetime, productionRunId int, statusCodeId int) 

insert @p values 
('1/1/2016 15:43:00', 1, 1), 
('1/1/2016 15:43:05', 1, 1), 
('1/1/2016 15:43:01', 2, 2), 
('1/1/2016 15:43:09', 2, 2), 
('1/1/2016 15:44:02', 2, 2), 
('1/1/2016 15:44:09', 2, 2), 
('1/1/2016 15:44:31', 3, 1), 
('1/1/2016 15:44:45', 3, 1) 

SELECT 
    productionRunId, 
    statusCodeId, 
    SUM(seconds) AS totalSeconds 
FROM (
    SELECT 
     p1.productionRunId, 
     p1.statusCodeId, 
     DATEDIFF(SECOND, MAX(p2.startTime), p1.startTime) AS seconds 
    FROM @p p1 
    INNER JOIN @p p2 ON p1.productionRunId = p2.productionRunId 
    AND p2.startTime < p1.startTime 
    GROUP BY 
     p1.startTime, 
     p1.productionRunId, 
     p1.statusCodeId 
) AS ElapsedPeriods 
GROUP BY 
    productionRunId, 
    statusCodeId 
+0

非常感谢!就是这样。 –

+0

@ ZackScriven - 如果这是/你的答案,请使用答案左侧的灰色复选框标记。 – Igor