根据某些条件以(HH:mm:ss)格式获取两个DateAndTime的持续时间

时间:2019-09-16 09:37:11

标签: sql sql-server tsql

DateAndTime in(HH:MM:SS)的持续时间,但我需要通过对某些条件进行排序来选择开始日期和结束日期,但持续时间却不正确

Start Date                     End date                  Duration
 2018-11-22 17:34:33.00   2018-11-26 10:22:57.00      09:36:48.0000000

在上面的示例中,DateDiffrence为98小时,但其计算为9小时?

(SELECT CONVERT(TIME, DATEADD(s, SUM(( DATEPART(hh, (B.DateAndTime - A.DateAndTime)) * 3600 ) + ( DATEPART(mi, (B.DateAndTime - A.DateAndTime)) * 60 ) + DATEPART(ss, (B.DateAndTime - A.DateAndTime))), 0)) AS total_time 
FROM (SELECT DateAndTime, ROW_NUMBER() OVER (ORDER BY DateAndTime ASC) AS S
      FROM Tablename
      WHERE Marker='S'
      and TagIndex=2
      AND a.Val=Val) AS A
INNER JOIN
(SELECT DateAndTime, ROW_NUMBER() OVER (ORDER BY DateAndTime ASC) AS E 
 FROM Tablename
 WHERE Marker='E'
 and TagIndex=2
 AND a.Val=Val) AS B
ON B.E=A.S) AS Duration)

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

SELECT RIGHT(CONVERT(varchar,(DATEDIFF(s,'2018-11-22 17:34:33.00','2018-11-26 10:22:57.00')) / 3600 ),2) + ':' 
          + RIGHT(CONVERT(varchar,(DATEDIFF(s,'2018-11-22 17:34:33.00','2018-11-26 10:22:57.00')) / 60) % 60 ,2) + ':' 
          + RIGHT(CONVERT(varchar,(DATEDIFF(s,'2018-11-22 17:34:33.00','2018-11-26 10:22:57.00')) % 60 ),2)