Forum Discussion

RBiems's avatar
RBiems
Copper Contributor
Dec 13, 2023
Solved

Transpose rows to columns

I have the table to the left, I would like to get the right table as a result, I don't know how many columns there will be, is this possible in SQL ? ID ep       ID EP1 EP2 EP3 EP4 etc....
  • RBiems's avatar
    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 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)

     

     

Resources