0

I have a table with ID and location columns and I'm trying to combine multiple rows into comma separated listed. For eg:

Source table:   ID    Location      Name
                 1        USA       Bob 
                 1        Brazil    Bob
                 1        Russia    Bob
                 2        India     Emily
                 2        China     Emily

My target table should get the values like this

Target table:   ID    Location             Name
                 1     USA, Brail, Russia  Bob
                 2     India, China        Emily

How can I Perform this using oracle 11g R2?

user1751356
  • 565
  • 4
  • 14
  • 33

1 Answers1

1

You can use listagg():

select id, listagg(location, ', ') within group (order by id) as location
from source
group by id

This does not guarantee the original ordering in the table. SQL tables are inherently unordered, so to guarantee this, you would need a distinct row id for each row. This following might get close:

select id, listagg(location, ', ') within group (order by seqnum) as location
from (select *, rownum as seqnum from source) s
group by id
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786