【问题标题】:listagg Oracle SQL Query, join on same tablelistagg Oracle SQL 查询,加入同一张表
【发布时间】:2017-03-04 01:04:29
【问题描述】:

对于每只狗,我想查找除狗之外的其他动物的匹配名称,并将它们添加到逗号分隔的列表中。表格图片及查询结果如下:

存在具有以下结构的表:

我想创建一个查询结果,例如:

【问题讨论】:

标签: sql oracle listagg


【解决方案1】:

您可以使用self-join,然后使用listagg

select tdog.animal,tdog.name
,listagg(tother.animal||'-'||tother.name||'-'||tother.id) within group(order by tother.id)
from tablename tdog
join tablename tother on tdog.name=tother.name and tdog.animal='dog' and tother.animal <> 'dog'
group by tdog.animal,tdog.name

【讨论】:

    【解决方案2】:

    有了一些技巧,你就不需要self join

    select 'dog' as animal, name,
           listagg(case when animal <> 'dog' then animal || '-' || name || '-' || id
                   end), ',') within group (order by id) as animals
    from t
    group by name
    having sum(case when animal = 'dog' then 1 else 0 end) > 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      相关资源
      最近更新 更多