0

How do I transpose my table this format in SQL?

This is the original column.

enter image description here

This is the transposed column.

enter image description here

Is this feasible in SQL?

Varsha
  • 59
  • 4
  • 3
    Yes, this is possible. But have you tried a query yet? – Tim Biegeleisen Apr 18 '18 at 05:18
  • It is possible. You need to pivot your table see this [example](https://blogs.msdn.microsoft.com/spike/2009/03/03/pivot-tables-in-sql-server-a-simple-sample/) or this [question](https://stackoverflow.com/q/1343145/8828524) If you don't want to aggregate the data. – virtualdvid Apr 18 '18 at 05:21

1 Answers1

3

If you don't mind NULL's in the resultset then you could also use a pivot for this.

Example snippet:

declare @T table (column1 int, column2 varchar(1));

insert  @T (column1, column2) values 
(1, 'a'), (1,'b'), (1,'c'), (1,'d'), 
(2, 'e'), (2,'f'), (2,'g'), (2,'h'),
(3, 'w'), (3,'e'),
(4, 'r'), (4,'t'), (4,'a'), (4,'s'), (4,'d'), (4,'f');

select *
from (
    select 
     column1,
     column2, 
     concat('c',row_number() over (partition by column1 order by (select 0))) as col
    from @T
) q
pivot (
 max(column2)
 for col in ([c1],[c2],[c3],[c4],[c5],[c6])
) pvt;

Result:

column1 c1   c2   c3   c4   c5   c6
------- ---- ---- ---- ---- ---- ----
1       a    b    c    d    NULL NULL
2       e    f    g    h    NULL NULL
3       w    e    NULL NULL NULL NULL
4       r    t    a    s    d    f

Disclaimer : A row_number that's ordered by nothing doesn't guarantee the same order in the result.

LukStorms
  • 28,916
  • 5
  • 31
  • 45
  • I like your variant. This one is easier to read and maintain – Alexander Volok Apr 18 '18 at 09:32
  • @AlexanderVolok Thanks. To be honest, pivot would be even easier if it wasn't required to hard-code those columnnames. But currently you would need to use dynamic sql for that. – LukStorms Apr 18 '18 at 09:38