问题
Possible Duplicate:
LISTAGG in oracle to return distinct values
I am using Oracle LISTAGG function but within my list of returned names I actually would like to eliminate duplicates and only return distinct values.
The query I have is something like this:
select a.id,
a.change_id,
LISTAGG(b.name, ',') WITHIN GROUP (ORDER BY b.name) AS "Product Name",
from table_a a,
table_b b
where a.id = 1
and b.change_id = c.change_id
group by a.id, a.change_id
At the moment, it is returning (just showing one record):
1 1 NameA, NameA, NameB, NameC, NameD, Name D
What I would like returned is:
1 1 NameA, NameB, NameC, Name D
回答1:
As the linked answers in the comment don't provide my flavor of solution, I'll post it anyway.
I'll only use table_b
with dummy data to show the concept, you can easily add your join etc.:
with table_b as ( -- dummy data
select 'name'||mod(level,3) name
,mod(level,3) id
from dual
connect by level < 10
union all
select 'name'||mod(level,2) name
,mod(level,3) id
from dual
connect by level < 10
)
select id
,RTRIM (
XMLAGG (
XMLELEMENT (E,XMLATTRIBUTES (name|| ',' AS "Seg")
)
ORDER BY name ASC
).EXTRACT ('./E[not(@Seg = preceding-sibling::E/@Seg)]/@Seg'),
','
) AS "Product Name"
,LISTAGG(b.name, ',') WITHIN GROUP (ORDER BY b.name) AS "Product Name with dups"
from table_b b
group by id;
(Idea taken from https://forums.oracle.com/forums/thread.jspa?messageID=9634767&tstart=0#9943367)
来源:https://stackoverflow.com/questions/11623713/eliminate-duplicates-using-oracle-listagg-function