Eliminate duplicates using Oracle LISTAGG function [duplicate]

半世苍凉 提交于 2019-12-02 04:39:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!