我有以下表StudentEntryDetails
:
Id StudId CheckTime CheckType
1 1 2015 - 01 - 08 09: 00: 00.000 IN
2 1 2015 - 01 - 08 11: 00: 00.000 OUT
3 1 2015 - 01 - 08 13: 00: 00.000 IN
4 1 2015 - 01 - 08 19: 00: 00.000 OUT
5 1 2015 - 01 - 09 08: 00: 00.000 IN
6 1 2015 - 01 - 09 12: 00: 00.000 OUT
7 1 2015 - 01 - 09 13: 00: 00.000 IN
8 1 2015 - 01 - 09 14: 00: 00.000 OUT
9 1 2015 - 01 - 10 08: 00: 00.000 IN
10 1 2015 - 01 - 10 15: 00: 00.000 OUT
11 2 2015 - 01 - 08 10: 00: 00.000 IN
12 2 2015 - 01 - 08 13: 00: 00.000 OUT
13 2 2015 - 01 - 13 07: 00: 00.000 IN
14 2 2015 - 01 - 13 13: 00: 00.000 OUT
15 2 2015 - 01 - 13 14: 00: 00.000 IN
16 2 2015 - 01 - 13 17: 00: 00.000 OUT
17 3 2015 - 01 - 09 12: 00: 00.000 IN
18 3 2015 - 01 - 09 14: 00: 00.000 OUT
我想要Min&每个日期和同一行中表中每个用户的最长时间 我写了以下代码
select StudId, Convert(date,CheckTime),
CheckInTime=min(case when CheckType='IN' then CheckTime end),
CheckOutTime=max(case when CheckType='OUT' then CheckTime end)
from StudentEntryDetails group by StudId,CheckTime
但是它给出了不正确的结果。我想要以下结果。
StudId Date CheckInTime CheckOutTime
1 2015-01-08 2015-01-08 09:00:00.000 2015-01-08 19:00:00.000
1 2015-01-09 2015-01-09 08:00:00.000 2015-01-09 14:00:00.000
1 2015-01-10 2015-01-10 08:00:00.000 2015-01-10 15:00:00.000
3 2015-01-09 2015-01-09 12:00:00.000 2015-01-09 14:00:00.000
2 2015-01-08 2015-01-08 10:00:00.000 2015-01-08 13:00:00.000
2 2015-01-13 2015-01-13 07:00:00.000 2015-01-13 17:00:00.000
答案 0 :(得分:1)
您需要GROUP BY StudId,Convert(date,CheckTime)
。像这样的东西
SELECT StudId, CONVERT(DATE,CheckTime),
CheckInTime = MIN(CASE WHEN CheckType='IN' THEN CheckTime END),
CheckOutTime = MAX(CASE WHEN CheckType='OUT' THEN CheckTime END)
FROM StudentEntryDetails
GROUP BY StudId,CONVERT(DATE,CheckTime)