0

Here's how my table looks

ID Name1 Name2 Name3
1  a     b       c 
1  c     d       a 
2  d     e       a 
2  c     d       b

I need one row per ID having distinct name1,name2,name3 in one row as a comma separated string.

ID Name 
1  a,c,b,d,c 
2  d,c,e,a,b

I have tried using listagg with distinct but not able to remove duplicates.

1 Answer 1

1

You need a subquery to remove the duplicates, something like;

select id, listagg(name, ',') within group (order by name) as names
from (
  select id, name1 as name from your_table
  union 
  select id, name2 as name from your_table
  union
  select id, name3 as name from your_table
)
group by id

The union will automatically remove duplicates from the combined result set (if you didn't want it to, you'd use union all).

As a demo with a CTE representing your table:

with your_table(id, name1, name2, name3) as (
  select 1,  'a', 'b', 'c' from dual 
  union all select 1, 'c', 'd', 'a' from dual
  union all select 2, 'd', 'e', 'a' from dual
  union all select 2, 'c', 'd', 'b' from dual
)
select id, listagg(name, ',') within group (order by name) as names
from (
  select id, name1 as name from your_table
  union 
  select id, name2 as name from your_table
  union
  select id, name3 as name from your_table
)
group by id;

ID NAMES              
-- --------------------
 1 a,b,c,d             
 2 a,b,c,d,e           

You could also have the subquery selecting all three columns and then pivoting them into rows, but with only three this might be simpler.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Alex. I don't know why I didn't think of this before. This worked!

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.