我有一个包含2列单位编号和周编号的表格如下。
+--------+------------+
| UnitID | WeekNumber |
+--------+------------+
| 235 | 1 |
| 235 | 2 |
| 235 | 3 |
| 236 | 3 |
| 237 | 1 |
| 237 | 3 |
+--------+------------+
我需要将其转换为以下格式
+--------+-------+-------+-------+
| UnitID | Week1 | Week2 | Week3 |
+--------+-------+-------+-------+
| 235 | 1 | 2 | 3 |
| 236 | NULL | NULL | 3 |
| 237 | 1 | NULL | 3 |
+--------+-------+-------+-------+
但是,我得到以下结果
+--------+-------+-------+-------+
| UnitID | Week1 | Week2 | Week3 |
+--------+-------+-------+-------+
| 235 | 1 | 2 | 3 |
| 236 | 3 | NULL | NULL |
| 237 | 1 | 3 | NULL |
+--------+-------+-------+-------+
以下是运行导致行为的样本测试的TSQL代码。
declare @temp table
(
UnitID int,
WeekNumber int
)
insert into @temp(UnitID, WeekNumber) values (235, 1)
insert into @temp(UnitID, WeekNumber) values (235, 2)
insert into @temp(UnitID, WeekNumber) values (235, 3)
insert into @temp(UnitID, WeekNumber) values (236, 3)
insert into @temp(UnitID, WeekNumber) values (237, 1)
insert into @temp(UnitID, WeekNumber) values (237, 3)
select * from @temp
;With cte As
(Select UnitID, WeekNumber,
Row_Number() Over(Partition By UnitID Order By WeekNumber asc) As rn
From @temp
)
Select UnitID, [1] As Week1, [2] As Week2, [3] As Week3
From cte
Pivot
(Max(WeekNumber) For rn In ([1], [2], [3])) As pvt;
您可以使用上面的代码填充临时表并查看结果。
答案 0 :(得分:2)
要获得您想要的结果,我不会使用row_number()
来创建列标题,我只会使用您当前的WeekNumber
值:
;With cte As
(
Select UnitID, WeekNumber,
'Week'+cast(weeknumber as varchar(2)) wn
From @temp
)
Select UnitID, [Week1], [Week2], [Week3]
From cte
Pivot
(
Max(WeekNumber)
For wn In ([Week1], [Week2], [Week3])
) As pvt;