繁体   English   中英

listagg Oracle SQL查询,在同一表上联接

[英]listagg Oracle SQL Query, join on same table

对于每条狗,我都希望找到除狗以外的其他动物的匹配名称,并将它们添加到以逗号分隔的列表中。 表的图像和查询的期望结果如下:

存在具有以下结构的表: 在此处输入图片说明

我想创建一个查询,其结果如下: 在此处输入图片说明

您可以使用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

使用一些技巧,您不需要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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM