0

I have a table that look like this:

ID Name
-------
1  John
1  Mary
1  Jane
2  John 
2  Mary
3  Jane

Knowing that every ID can only contain up to three names, I want to use a SELECT statement to turn this into the following:

ID Name1 Name2 Name3
--------------------
1  John  Mary  Jane
2  John  Mary
3  Jane

Is there a way to do this in SQL?

3
  • Which db are you using? Oracle ? Commented Mar 24, 2015 at 15:54
  • 2
    You need to look at using a PIVOT, whose syntax is database-specific. Commented Mar 24, 2015 at 15:57
  • I think this is a duplicate: stackoverflow.com/questions/19280591/oracle-pivot-operator Commented Mar 24, 2015 at 16:28

2 Answers 2

1

If you know that there are at most three names, you can do this using conditional aggregation:

select id,
       max(case when seqnum = 1 then name end) as name1,
       max(case when seqnum = 2 then name end) as name2,
       max(case when seqnum = 3 then name end) as name3
from (select t.*, row_number() over (partition by id order by name) as seqnum
      from table t
     ) t
group by id;
Sign up to request clarification or add additional context in comments.

Comments

0

With Oracle, you can use the PIVOT feature.

However, you'll need to RANK your rows first, over id-name pairs, and then you can do the pivot directive for (literally) the rank you just generated.

Pages to read:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.