如何在sql server 2014中计算持续时间?

时间:2017-03-30 08:05:07

标签: sql-server stored-procedures

This is my result I want to calculate time duration between checkin and checkout like for example

  

这是我的第一个条件。假设CheckIn时间大于退房时间,那么如何计算时间持续时间

StaffName | attendDate| staffid| firmId| Shiftname | AttendId| CheckIn| CheckOut | Total Duration
---------------------------------------------------------------------------------------------
Kiran A Veri  |   2017-03-28   |5146  |1  | Night  | 34584   |18:00:00| 03:00:00  | 09:00:00
  

这是我的第二个条件。如果入住时间小于结账时间,那么如何在此查询中管理这两个条件?

 StaffName | attendDate| staffid| firmId| Shiftname | AttendId| CheckIn| CheckOut | Total Duration
    ---------------------------------------------------------------------------------------------
    Ritesh B Patel  |   2017-03-28   |5146  |1  | General | 34584   |10:06:06| 19:35:46  | 09:29:00

1 个答案:

答案 0 :(得分:1)

第一部分:

使用CheckIn>时的情况CheckOut与DATEDIFF一起使用。

第二部分:

使用Style = 108(hh.mm.ss)构建日期时间或时间字段并convert

CREATE TABLE TEST(ID int, CheckIn time, CheckOut time);
INSERT INTO TEST VALUES(1, '03:00:00', '10:00:00'),(2, '10:26:13', '03:12:15'),(3, '18:00:00', '03:00:00');

-- Below SQL-Server 2012
SELECT CASE WHEN CheckIn > CheckOut
            THEN CONVERT(VARCHAR(20), 86400 - DATEADD(SECOND, DATEDIFF(SECOND, CheckOut, CheckIn), '00:00:00'), 108)
            ELSE CONVERT(VARCHAR(20),DATEADD(SECOND, DATEDIFF(SECOND, CheckIn, CheckOut), '00:00:00'), 108)
            END Elapsed_Time
FROM   TEST

-- SQL-Server 2012 or above
SELECT CASE WHEN CheckIn > CheckOut
            THEN FORMAT(86400 - DATEADD(SECOND, DATEDIFF(SECOND, CheckOut, CheckIn), '00:00:00'), 'hh\:mm\:ss')
            ELSE FORMAT(DATEADD(SECOND, DATEDIFF(SECOND, CheckIn, CheckOut), '00:00:00'), 'hh\:mm\:ss')
            END Elapsed_Time
FROM   TEST

GO
| Elapsed_Time |
| :----------- |
| 07:00:00     |
| 16:46:02     |
| 09:00:00     |

| Elapsed_Time |
| :----------- |
| 07:00:00     |
| 04:46:02     |
| 09:00:00     |

dbfiddle here