I have a table with 2 columns Unit Number and Week Number as below.
+--------+------------+
| UnitID | WeekNumber |
+--------+------------+
| 235 | 1 |
| 235 | 2 |
| 235 | 3 |
| 236 | 3 |
| 237 | 1 |
| 237 | 3 |
+--------+------------+
I need it trasformed to the following format
+--------+-------+-------+-------+
| UnitID | Week1 | Week2 | Week3 |
+--------+-------+-------+-------+
| 235 | 1 | 2 | 3 |
| 236 | NULL | NULL | 3 |
| 237 | 1 | NULL | 3 |
+--------+-------+-------+-------+
However, I am getting the following result
+--------+-------+-------+-------+
| UnitID | Week1 | Week2 | Week3 |
+--------+-------+-------+-------+
| 235 | 1 | 2 | 3 |
| 236 | 3 | NULL | NULL |
| 237 | 1 | 3 | NULL |
+--------+-------+-------+-------+
Here is the TSQL code to run a sample test that resulted in the behavior.
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;
You can use the above code the populate a temp table and see the results.
To get the result that you want I wouldn't use row_number()
to create your column headers, I would just use your current values of 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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.