Rajesh Biswas
Rajesh Biswas

Reputation: 242

SQL Grouped Rows as Column

I need help to change grouped row as column.

ColGroup      Code            
===================
1        A001
1        A001
1        A001   
2        A002
2        A002
3        A003

Into

1         2       3
===================
A001    A002    A003
A001    A002 
A001 

Thank you for any help.

Upvotes: 0

Views: 72

Answers (2)

Jagadesh jakes
Jagadesh jakes

Reputation: 85

I had tried this.I didn't got the exact result but this may be helpful to you http://www.sqlfiddle.com/#!9/4ecf6c/4

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1269543

You can do this using conditional aggregation:

select max(case when colgroup = 1 then code end) as [1],
       max(case when colgroup = 2 then code end) as [2],
       max(case when colgroup = 3 then code end) as [3]
from (select t.*,
             row_number() over (partition by colgroup order by (select null)) as seqnum
      from t
     ) t
group by seqnum
order by seqnum;

Upvotes: 2

Related Questions