Abhishek Yadav
Abhishek Yadav

Reputation: 21

Combine multiple rows to single row group by Specific column

I have a table that looks similar to this here:

enter image description here

I would like to able to combine all that data when they have the same Id.

Which would look like this:

enter image description here

Upvotes: 0

Views: 52

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269563

Use conditional aggregation:

select id,
       max(case when seqnum = 1 then section end) as section1,
       max(case when seqnum = 1 then value1 end) as section1_value1,
       max(case when seqnum = 1 then value2 end) as section1_value2,
       max(case when seqnum = 2 then section end) as section2,
       max(case when seqnum = 2 then value1 end) as section2_value1,
       max(case when seqnum = 2 then value2 end) as section2_value2
from (select t.*,
             row_number() over (partition by id order by section) as seqnum
      from t
     ) t
group by id;

Upvotes: 1

Related Questions