【问题标题】:Is there any way to use DISTINCT in xmlagg function in sql?有没有办法在 sql 的 xmlagg 函数中使用 DISTINCT?
【发布时间】:2021-01-15 09:31:05
【问题描述】:

我使用了以下命令。

select col1, col2, XMLAGG(XMLELEMENT(E, colname || ',')).EXTRACT('//text()')
from table
group by col1, col2

输出:

col1      col2      col3

KOCHI   ERNAKULAM   residential, commercial, residential, residential

但我需要以下输出

col3 :

residential, commercial.

我尝试在子查询中使用 DISTINCT,但没有获得所需的输出。有什么帮助吗?

【问题讨论】:

  • 是的。 Oracle 数据库 11g 企业版 11.2.0.3.0 版

标签: sql oracle oracle11g


【解决方案1】:

您可以在子查询中使用distinct,如下所示:

select col1, col2, XMLAGG(XMLELEMENT(E, colname || ',')).EXTRACT('//text()')
from (select distinct col1, col2, colname from table)
group by col1, col2

【讨论】:

    【解决方案2】:

    首先选择不同的值,然后应用XMLAGG,例如

    select col1, col2, XMLAGG(XMLELEMENT(E, colname || ',')).EXTRACT('//text()')
    from (select distinct col1, col2, colname
          from table 
         )
    group by col1, col2
    

    不过,如果结果字符串不超过 4000 个字符,请考虑使用LISTAGG

    select col1, col2, LISTAGG(colname, ',')) within group (order by null)
    from (select distinct col1, col2, colname
          from table 
         )
    group by col1, col2
    

    【讨论】:

      【解决方案3】:

      虽然DISTINCT 的子查询在这种情况下有效,但它不是一个通用的解决方案。它可能会干扰您可能希望包含在查询中的其他列。

      XMLAGG() 忽略 NULL 值。所以更通用的方法是使用ROW_NUMBER()

      select col1, col2,
             XMLAGG(CASE WHEN SEQNUM. = 1 THEN XMLELEMENT(E, colname || ',') END).EXTRACT('//text()')
      from (select t.*,
                   ROW_NUMBER() OVER (PARTITION BY col1, col2, colname ORDER BY colname) as seqnum
            from t
           ) t
      group by col1, col2
      

      【讨论】:

        【解决方案4】:

        使用regexp_replace 函数怎么样?例如

        select
        col1,
        col2,
        regexp_replace(XMLAGG(XMLELEMENT(E, colname || ',')).EXTRACT('//text()'),'([^,]+)(,\1)+', '\1') as colname_list
        from table
        group by col1, col2
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-06-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-09
          • 2014-09-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多