How to use Oracle's LISTAGG function with a unique filter? [duplicate] How to use Oracle's LISTAGG function with a unique filter? [duplicate] oracle oracle

How to use Oracle's LISTAGG function with a unique filter? [duplicate]


I don't have an 11g instance available today but could you not use:

SELECT group_id,       LISTAGG(name, ',') WITHIN GROUP (ORDER BY name) AS names  FROM (       SELECT UNIQUE              group_id,              name         FROM demotable       ) GROUP BY group_id


Super simple answer - solved!

my full answer here it is now built in in some oracle versions.

select group_id, regexp_replace(    listagg(name, ',') within group (order by name)    ,'([^,]+)(,\1)*(,|$)', '\1\3')from demotablegroup by group_id;  

This only works if you specify the delimiter to ',' not ', ' ie works only for no spaces after the comma. If you want spaces after the comma - here is a example how.

select replace(    regexp_replace(     regexp_replace('BBall, BBall, BBall, Football, Ice Hockey ',',\s*',',')                ,'([^,]+)(,\1)*(,|$)', '\1\3'),',',', ') from dual

gives BBall, Football, Ice Hockey


create table demotable(group_id number, name varchar2(100));insert into demotable values(1,'David');insert into demotable values(1,'John');insert into demotable values(1,'Alan');insert into demotable values(1,'David');insert into demotable values(2,'Julie');insert into demotable values(2,'Charles');commit;select group_id,        (select listagg(column_value, ',') within group (order by column_value) from table(coll_names)) as namesfrom (  select group_id, collect(distinct name) as coll_names     from demotable    group by group_id )GROUP_ID    NAMES1   Alan,David,John2   Charles,Julie