listagg Oracle SQL Query,连接在同一个表上

时间:2017-03-04 01:04:30

标签: sql oracle listagg

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

存在具有此结构的表: enter image description here

我想创建一个包含以下结果的查询: enter image description here

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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