Forum Discussion
Transpose rows to columns
- Dec 14, 2023
Solution was actually easier then I though.
First I added an extra column with
'EP' + CAST(ROW_NUMBER() OVER(PARTITION by ID ORDER BY ID) as nvarchar(10)) as RNK
and then a simple dynamic pivotDECLARE @query AS NVARCHAR(MAX)='',
@colsPivot as NVARCHAR(MAX)='';CREATE TABLE #TMP3 (ID nvarchar(10), subject bigint, RNK Nvarchar(10));
insert into #TMP3 select ID, subject, 'EP' + CAST(ROW_NUMBER() OVER(PARTITION by ID ORDER BY ID) as nvarchar(10)) as RNK FROM #TMP2SELECT @colspivot = @Colspivot + quotename(rnk) + ',' from (select distinct rnk from #TMP3) as tmp3
select @colsPivot = substring(@colspivot, 0, Len(@colspivot))
select @colspivot
Set @query = 'SELECT * FROM
(select id,subject,rnk from #tmp3) T1
pivot
(SUM(Subject) for rnk in (' + @colsPivot + ')
) T2'execute(@query)
Solution was actually easier then I though.
First I added an extra column with
'EP' + CAST(ROW_NUMBER() OVER(PARTITION by ID ORDER BY ID) as nvarchar(10)) as RNK
and then a simple dynamic pivot
DECLARE @query AS NVARCHAR(MAX)='',
@colsPivot as NVARCHAR(MAX)='';
CREATE TABLE #TMP3 (ID nvarchar(10), subject bigint, RNK Nvarchar(10));
insert into #TMP3 select ID, subject, 'EP' + CAST(ROW_NUMBER() OVER(PARTITION by ID ORDER BY ID) as nvarchar(10)) as RNK FROM #TMP2
SELECT @colspivot = @Colspivot + quotename(rnk) + ',' from (select distinct rnk from #TMP3) as tmp3
select @colsPivot = substring(@colspivot, 0, Len(@colspivot))
select @colspivot
Set @query = 'SELECT * FROM
(select id,subject,rnk from #tmp3) T1
pivot
(SUM(Subject) for rnk in (' + @colsPivot + ')
) T2'
execute(@query)