如何获得时间总和

时间:2017-05-31 04:17:33

标签: sql-server

我正在使用SQL Server 2014.我的表有两列。第一列数据类型是datetime,第二列数据类型是nvarchar,有两种类型的数据,失败和成功。在这里,我提供了一个示例数据:

 Column 1               | Column 2  
------------------------+--------------
2017-05-25 05:30:36.950 | Success  
2017-05-25 06:00:37.117 | Success  
2017-05-25 06:30:37.077 | Success  
2017-05-26 03:00:37.227 | Fail  
2017-05-26 03:30:45.143 | Fail  
2017-05-26 04:00:36.793 | Success  
2017-05-26 04:30:36.957 | Success  

如何及时获得Success行的总和以及Fail行的总和。例如,正如您在上面的示例数据中所看到的,我需要一个查询,可以计算成功行1小时30分钟,失败行30分钟。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,这就是你需要的。

DECLARE @SampleData AS TABLE
(
    Column1 datetime, 
    Column2 varchar(20)
)

INSERT INTO @SampleData (Column1,Column2)
VALUES
( '2017-05-25 05:30:36.950', 'Success'),  
( '2017-05-25 06:00:37.117', 'Success'),  
( '2017-05-25 06:30:37.077', 'Success'),  
( '2017-05-26 03:00:37.227', 'Fail'),  
( '2017-05-26 03:30:45.143', 'Fail'),  
( '2017-05-26 04:00:36.793', 'Success'),  
( '2017-05-26 04:30:36.957', 'Success')
;WITH temp AS
(
    SELECT  *,
          lag(sd.Column2) over(ORDER BY sd.Column1) AS PreviousColumn2,
          lag(sd.Column1) over(ORDER BY sd.Column1) AS PreviousColumn1
    FROM @SampleData sd
)

SELECT t.Column2,sum(datediff(minute,t.PreviousColumn1, t.Column1)) AS TotalMinutes 
FROM temp t
WHERE t.Column2 = t.PreviousColumn2
GROUP BY t.Column2

返回

Column2 TotalMinutes
Fail    30
Success 90

参考:LAG Window function