可以轉動的,如下下面
select * from (
select *, RowN = row_number() over(partition by pid order by Category) from Categories
) a
pivot (max(category) for RowN in ([1],[2],[3])) p
輸出:
+-----+-----------+-----------+-----------+
| Pid | Category1 | Category2 | Category3 |
+-----+-----------+-----------+-----------+
| 1 | a | b | NULL |
| 2 | a | b | NULL |
| 3 | a | b | c |
+-----+-----------+-----------+-----------+
因爲你可以按照以下使用的列的動態列表:
declare @cols1 varchar(max)
declare @cols2 varchar(max)
declare @query nvarchar(max)
--Row Numbers with tally
;with c1 as (
select * from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) v(n))
,c2 as (select n1.* from c1 n1, c1 n2, c1 n3, c1 n4)
,RowNumbers as (
select top (select max(cnt) from (select cnt = count(*) from Categories group by pid) a) convert(varchar(6), row_number() over (order by (select null))) as RowN
from c2 n1, c2 n2
)
select @cols1 = stuff((select ','+QuoteName(RowN) from RowNumbers group by RowN for xml path('')),1,1,''),
@cols2 = stuff((select ',' + QuoteName(RowN) + ' as '+ QuoteName(concat('Category' , RowN)) from RowNumbers group by RowN for xml path('')),1,1,'')
select @cols1, @cols2
Set @query = ' Select Pid, '+ @cols2 +' from ('
Set @query += ' select *, RowN = row_number() over(partition by pid order by Category) from Categories) a '
Set @query += ' pivot (max(category) for RowN in (' + @cols1 + ')) p'
--select @query
exec sp_executesql @query
你會怎麼做一個像一行4'| b | c | '? – SqlZim
所有的最佳選擇是將這些數據永久歸一化。然後它變得微不足道。當你有像category1,category2這樣的列時,你通過重複組違反了1NF。 –
我認爲你想unpivot沒有透視,這將正常化更好,由@SeanLange建議 – scsimon