[datetime2](7)的DateDiff,格式为hh:mm; ss

时间:2019-02-21 08:49:44

标签: sql sql-server

[8,0,0,0,0], [0,11,0,0,0], [0,8,0,0,0], [0,0,7,0,0], [0,0,0,9,0], [0,0,0,0,10]

以下是要根据预期结果修改的查询

CREATE TABLE dbo.Duration     (startDate datetime2, endDate datetime2);

INSERT INTO dbo.Duration (startDate, endDate)  VALUES ('2007-05-06 16:42:09', '2007-05-07 11:10:08');  
INSERT INTO dbo.Duration (startDate, endDate)  VALUES ('2007-05-07 08:30:09', '2007-05-07 12:12:43');  
INSERT INTO dbo.Duration (startDate, endDate)  VALUES ('2007-05-07 11:35:09', '2007-05-07 17:13:39');  

预期结果:

19:32:01
04:18:34
06:22:29

2 个答案:

答案 0 :(得分:0)

您可以尝试以下查询。

SELECT CONVERT(VARCHAR(12), DATEADD(MS, DATEDIFF(MS,startDate, endDate), 0), 108) AS TimeDiff from Duration

答案 1 :(得分:0)

尝试如下

with cte as
(
select    DATEDIFF(second, startDate, endDate) AS Duration      FROM dbo.Duration
) select Duration AS 'seconds',
   CONVERT(varchar(20), DATEADD(second, Duration, 0), 108) AS 'hh:mm:ss' from cte

demo link

seconds hh:mm:ss
66479   18:27:59
13354   03:42:34
20310   05:38:30