0

I can concatenate column values from multiple rows in Oracle using LISTAGG

But I want to avoid duplicates

Currently it return duplicates

select LISTAGG( t.id,',') WITHIN GROUP (ORDER BY t.id) from table t;

for example for data

ID
10
10
20
30
30
40

Returns 10,10,20,30,40,40

Instead 10,20,30,40

And I can't use distinct inside LISTAGG

select LISTAGG( distinct t.id,',') WITHIN GROUP (ORDER BY t.id) from table t;

Error

ORA-30482: DISTINCT option not allowed for this function
Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
Ori Marko
  • 56,308
  • 23
  • 131
  • 233

2 Answers2

2

One option would be using regexp_replace():

select regexp_replace(
                      listagg( t.id,',') within group (order by t.id)
                      , '([^,]+)(,\1)+', '\1') as "Result"
  from t

Demo

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
1

You can put the distinct in a subquery:

select LISTAGG( t.id,',') WITHIN GROUP (ORDER BY t.id) from (SELECT DISTINCT t.id FROM TABLE) t
Radagast81
  • 2,921
  • 1
  • 7
  • 21