0

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

This is My First Condition. suppose CheckIn Time is Greater Than Check Out Time so How Can I calculate Time Duration

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

This is my second condition. If check in time is less than checkout time so how to manage both condition in this Query?

 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
6
  • What is the type of the CheckIn and CheckOut columns? Mar 30, 2017 at 8:06
  • Check in and check out is a time Mar 30, 2017 at 8:07
  • @TimBiegeleisen CheckIn is Time and checkOut also Time Please Send me Query How to calculate Total Duration Mar 30, 2017 at 8:09
  • Which sql-server version?
    – McNets
    Mar 30, 2017 at 8:14
  • @McNets Sql Server 2014 Mar 30, 2017 at 9:27

1 Answer 1

1

For the first part:

Use a CASE WHEN CheckIn > CheckOut in conjunction with DATEDIFF.

For the second part:

Build a datetime or time field and convert it using Style=108 (hh.mm.ss)

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

2
  • See suppose My CheckIn time is 18:00:00 and CheckOut Time is 03:00:00 so my total duration is 09:00:00 But its Showing 15:00:00 Mar 30, 2017 at 9:50
  • edited, check it now
    – McNets
    Mar 30, 2017 at 9:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.