简体   繁体   English

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

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

For every dog, I'd like to find the matching names of other animals besides dog, and add them in a comma-separated list. 对于每条狗,我都希望找到除狗以外的其他动物的匹配名称,并将它们添加到以逗号分隔的列表中。 Images of table and desired results of query below: 表的图像和查询的期望结果如下:

A table exists with this structure: 存在具有以下结构的表: 在此处输入图片说明

And I would like to create a query with results such as: 我想创建一个查询,其结果如下: 在此处输入图片说明

You can use a self-join and then a listagg . 您可以使用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

With some tricks, you don't need a self join : 使用一些技巧,您不需要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