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 ?

IDep   IDEP1EP2EP3EP4etc...
167   167118132234 
1118   212344950100 
1132   3123321456  
1234         
21234         
249         
250         
2100         
3123         
3321         
3456         

 

 

 

  • 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)

     

     

1 Reply

  • RBiems's avatar
    RBiems
    Copper Contributor

    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