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)
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.
2
Answers
This can be done using the conditional aggregation based on the date part using the aggregate function
MAX()
:Results :
Demo here
Try a query like this: