我正在尝试找到一种方法来转换我将表中所有列排序为行的表
EmpID Day StartTime
-------------------------------------------------
4 SUNDAY 10:00:00 AM
4 MONDAY 8:00:00 AM
4 TUESDAY 8:00:00 AM
4 WEDNESDAY 8:00:00 AM
4 THURSDAY 8:00:00 AM
4 FRIDAY NULL
4 SATURDAY NULL
800 SUNDAY 10:00:00 AM
800 MONDAY 8:00:00 AM
800 TUESDAY 8:00:00 AM
800 WEDNESDAY 8:00:00 AM
800 THURSDAY 8:00:00 AM
800 FRIDAY NULL
800 SATURDAY NULL
INTO
EmpID Sunday(Start Time) Monday(Start Time)
-------------------------------------------------
4 10:00:00 AM 8:00:00 AM
等...
我已经看到了Pivot和Unpivot的示例,但是对于Pivot / Unpivot函数,这会很复杂吗?
如果您想使用PIVOT
示例
Select *
From YourTable src
Pivot ( max(StartTime) for Day in ([Sunday],[Monday],[Tuesday] ) ) pvt
注:假定YourTable
是示例中显示的3列。如果您有多余的列,则YourTable
应替换为子查询,例如
From (Select EmpID,Day,StartTime From YourTable) src
我只使用条件聚合:
select empid,
max(case when day = 'Sunday' then StartTime end) as Sunday_StartTime,
max(case when day = 'Monday' then StartTime end) as Monday_StartTime,
. . .
from t
group by empid;