下面是我的带有示例数据的SQL Server表结构:
DateValue Status EmpId
----------------------------------------
2018-05-28 8:00 01 2000347
2018-05-28 20:18 02 2000347
2018-05-28 8:00 01 2000348
2018-05-28 17:18 02 2000348
我想要这样的输出:
sEmpId Status (1) IN Time Status (2) Out Time
---------------------------------------------------------------
2000347 2018-05-28 08:00:00.000 2018-05-28 20:18:00.000
2000348 2018-05-28 08:00:00.000 2018-05-28 17:18:00.000
您可以在这里找到我的尝试-Row To Column
我遇到以下错误
错误,警告:
'01'附近的语法不正确。
答案 0 :(得分:5)
通常,标识符不能以数字开头。您需要使用[]
select sEmpId, [01], [02]
from
(
select sEmpId,dDateTime,sStatus
from #temp
) d
pivot
(
max(dDateTime)
for sStatus in ([01], [02])
) piv;
答案 1 :(得分:2)
Select
sEmpId,
Max(Case When sStatus = '01' Then dDateTime End) As [In],
Max(Case When sStatus = '02' Then dDateTime End) As [Out]
From #temp
Group By sEmpId
答案 2 :(得分:1)
或者,如果进出时间在同一天,则可以使用以下查询:
select sEmpId,
min(dDateTime) InTime,
max(dDateTime) OutTime
from #temp
group by sEmpId, day(dDateTime)