SQL

时间:2018-10-08 04:33:06

标签: sql sql-server database ssms

我编写了此SQL查询:

SELECT TOP (15) UserName, EventName, EventTime
FROM AttendanceEvents
WHERE UserName = 'Kareem'

结果为:

enter image description here

如何将事件的值分成新的列?

我想要的输出是:

UserName | Login                | LogOut
Kareem    2015-04-13 01:43       2015-04-13 13:44
Kareem    2015-04-18 12:39       NULL
Kareem    2015-04-18 12:43       NULL
.
.
.
Kareem    2015-04-25 00:35       2015-04-25 05:21

1 个答案:

答案 0 :(得分:3)

通过占用分钟数来使用条件聚合

select username,cast(eventtime as date) as d, min(case when eventname='IN' then eventtime end) as login,
min(case when eventname='OUT' then eventtime end) as logout
from tablename
group by username,cast(eventtime as date)