【问题标题】:Eliminate duplicates using Oracle LISTAGG function [duplicate]使用 Oracle LISTAGG 函数消除重复项 [重复]
【发布时间】:2012-07-22 08:22:24
【问题描述】:

可能重复:
LISTAGG in oracle to return distinct values

我正在使用 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

【问题讨论】:

标签: sql oracle plsql analytics oracle11gr2


【解决方案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

【讨论】:

  • 与简单的LISTAGG 解决方案相比,这一定很慢......但是,我喜欢它!
  • @LukasEder:是的,这可能会更慢,但是LISTAGG 没有DISTINCT,所有其他解决方案要么进行两次全表扫描,要么使用也比LISTAGG 慢的正则表达式。 (感谢喜欢)
  • 我不确定是否仅仅因为应用了DISTINCT而引入了全表扫描?使用LISTAGG(或任何其他列出组内所有元素的聚合方法),无论如何都会不可避免地进行全表扫描,缺少“列出”字段上的索引......我可以想象DISTINCT in a subselect 效果最好,但这只是猜测
  • @LukasEder:正确,但我不仅仅指DISTINCT。我想到了需要多列的子选择,但答案from your link 提供了一个不错的解决方案,使用 row_number()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 2021-08-04
  • 1970-01-01
  • 2022-01-06
  • 2020-04-19
  • 1970-01-01
  • 2018-11-28
相关资源
最近更新 更多