Here the question,
I have a table called attendance with 4 columns:
[Username] varchar(256)
[Date] varchar(256)
[Time] varchar(256)
[Action] varchar(256)
What I wish to achieve is to get the first Check In and out time and Last Check In and out time. If there is only one Check In and out row in the table, it return the same.
Sample data like this:
Username | Date | Time | Action
--------------------------------------------
User1 | 01/12/2012 | 12:54:41 | Check In
User1 | 01/12/2012 | 18:26:36 | Check Out
User1 | 01/12/2012 | 18:44:17 | Check In
User1 | 01/12/2012 | 22:05:31 | Check Out
My expected result show below:
Output:
Username | Date | First In | First Out | Last In | Last Out
User1 | 01/12/2012 | 12:54:41 | 18:26:36 | 18:44:17 | 22:05:31
I tried with this SQL statement:
SELECT [USERNAME], [DATE]
, min(case when [action] = 'Clock In' then [time] else '' end) as 'First in'
, min(case when [action] = 'Clock Out' then [time] else '' end )as 'First out'
, max(case when [action] = 'Clock In' then [time] else '' end) as 'Last in'
, max(case when [action] = 'Clock Out' then [time] else '' end )as 'Last out'
FROM attendance
WHERE [USERNAME] = 'User1' AND [DATE] = '01/12/2012'
group by [username],[date]
It returns unexpected result that my min value always ” or empty but both my max value
‘Last in’ and ‘Last Out’ is in correct value.
Output:
Username | Date | First In | First Out | Last In | Last Out
User1 | 01/12/2012 | | | 18:44:17 | 22:05:31
Is there any wrong with my SQL?
Can anyone give any suggestion?
Try this:
Are you understand where is the problem?