Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

group clock in and clock out attendance query

I have Attendance table:

EmpId DateEntry AttType
E-0001 2024-01-01 08:00:02 IN
E-0001 2024-01-01 17:01:00 OUT
E-0002 2024-01-01 07:59:02 IN
E-0002 2024-01-01 17:00:07 OUT

How to query this table into:

DateEntry EmpID ClockIn ClockOut
2024-01-01 E-0001 08:00:02 17:01:00
2024-01-01 E-0002 07:59:02 17:00:07

where the ClockIn/ClockOut is based on AttType (when ‘IN’ then ClockIn, when ‘OUT’ then ClockOut)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried this query :

SELECT EmpID,
       DateEntry,
       CASE
           WHEN AttType = 'IN' THEN DateEntry
           ELSE NULL
       END AS ClockIn,
       CASE
           WHEN AttType = 'OUT' THEN DateEntry
           ELSE NULL
       END AS ClockOut
FROM Attendance
GROUP BY EmpID,
         DateEntry; 

but the results was:

DateEntry EmpID ClockIn ClockOut
2024-01-01 E-0001 08:00:02
2024-01-01 E-0001 17:01:00
2024-01-01 E-0002 07:59:02
2024-01-01 E-0002 17:00:07

how to get the correct result? anyone can help me? thank you.

>Solution :

This can be done using the conditional aggregation based on the date part using the aggregate function MAX() :

SELECT DATE(DateEntry) AS DateEntry,
       EmpID,
       MAX(CASE
           WHEN AttType = 'IN' THEN TIME(DateEntry)
           ELSE NULL
       END) AS ClockIn,
       MAX(CASE
           WHEN AttType = 'OUT' THEN TIME(DateEntry)
           ELSE NULL
       END) AS ClockOut
FROM Attendance
GROUP BY EmpID,
         DATE(DateEntry); 

Results :

DateEntry   EmpID   ClockIn     ClockOut
2024-01-01  E-0001  08:00:02    17:01:00
2024-01-01  E-0002  07:59:02    17:00:07

Demo here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading