당신이 피벗 수만큼 아래에 출력
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
아래 :
당신은 다음과 같이 사용할 수있는 열 동적 목록 (210)
+-----+-----------+-----------+-----------+
| 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를 위반합니다. –
나는 피벗하지 않는 피벗을 원한다고 생각합니다. @SeanLange가 제안한대로 더 정상화 될 것입니다. – scsimon