Skip to content
Advertisement

I have multiple entry and exit status of a person. how do i get the last status of single person

I have a table in sql in following format

Userid  Status  Logtime
1         In    10:10
1         In    10:12
2         In    10:14
3         In    10:16
3         Out   10:18
1         Out   10:20
4         In    10:22
2         Out   10:24

Output required

Userid  Status  In_time Out_time
1         out            10:20
2         In    10:14    10:24
3         In    10:16    10:18
4         In    10:22   

Advertisement

Answer

In_Time should be the first instead of the last status.

Then your result should be instead

Userid IN_TIME OUT_TIME

1       10:10   10:20
2       10:14   10:24
3       10:16   10:18
4       10:22   NULL

Code like below, live demo here

SELECT Userid,
MIN(CASE WHEN sStatus = 'IN' THEN Logtime ELSE NULL END) AS IN_TIME, 
MAX(CASE WHEN sStatus = 'Out' THEN Logtime ELSE NULL END) OUT_TIME
FROM TblInOut
GROUP BY Userid

Updated

If you want to get the last status for In_Time, just adjust slightly condition from Min to Max like below, live demo here

SELECT Userid,
       MAX(CASE WHEN sStatus = 'IN' THEN Logtime ELSE NULL END) AS IN_TIME, 
       MAX(CASE WHEN sStatus = 'Out' THEN Logtime ELSE NULL END) OUT_TIME
FROM TblInOut
GROUP BY Userid

Output

Userid  IN_TIME OUT_TIME
1       10:12   10:20
2       10:14   10:24
3       10:16   10:18
4       10:22   NULL
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement