【问题标题】:concatenate column values from multiple rows in Oracle without duplicates连接Oracle中多行的列值而没有重复
【发布时间】:2020-03-28 23:58:55
【问题描述】:

我可以使用LISTAGGconcatenate column values from multiple rows in Oracle

但我想避免重复

目前它返回重复项

select LISTAGG( t.id,',') WITHIN GROUP (ORDER BY t.id) from table t;

例如数据

ID
10
10
20
30
30
40

返回10,10,20,30,40,40

改为10,20,30,40

我不能在LISTAGG 中使用distinct

select LISTAGG( distinct t.id,',') WITHIN GROUP (ORDER BY t.id) from table t;

错误

ORA-30482: DISTINCT option not allowed for this function

【问题讨论】:

    标签: sql oracle duplicates string-concatenation listagg


    【解决方案1】:

    一种选择是使用regexp_replace()

    select regexp_replace(
                          listagg( t.id,',') within group (order by t.id)
                          , '([^,]+)(,\1)+', '\1') as "Result"
      from t
    

    Demo

    【讨论】:

    【解决方案2】:

    您可以将 distinct 放在子查询中:

    select LISTAGG( t.id,',') WITHIN GROUP (ORDER BY t.id) from (SELECT DISTINCT t.id FROM TABLE) t
    

    【讨论】:

    • 感谢您的回答,这是复杂查询的一部分,我想知道是否可以在没有其他子查询的情况下做到这一点?
    猜你喜欢
    • 2016-11-24
    • 2014-01-02
    • 2012-09-15
    • 2013-10-27
    • 1970-01-01
    • 2011-06-08
    • 2014-03-03
    • 1970-01-01
    • 2012-10-19
    相关资源
    最近更新 更多