3

可能重复:
oracle 中的 LISTAGG 以返回不同的值

我正在使用 Oracle LISTAGG 函数,但在我的返回名称列表中,我实际上想消除重复项,只返回不同的值。

我的查询是这样的:

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

目前,它正在返回(仅显示一条记录):

1    1   NameA, NameA, NameB, NameC, NameD, Name D

我想要返回的是:

1    1   NameA, NameB, NameC, Name D
4

1 回答 1

1

由于评论中的链接答案没有提供我的解决方案,我还是会发布它。

我只会使用table_b虚拟数据来展示这个概念,您可以轻松添加您的连接等:

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;

(想法取自https://forums.oracle.com/forums/thread.jspa?messageID=9634767&tstart=0#9943367

于 2012-07-24T07:02:30.887 回答