2017-03-04 68 views
0

對於每隻狗,我想找到除狗以外的其他動物的匹配名稱,並將它們添加到逗號分隔列表中。表圖像和下面的查詢期望的結果:listagg Oracle SQL Query,加入同一張表

一個表,這種結構存在: enter image description here

而且我想創建結果,如查詢: enter image description here

+0

請仔細閱讀http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload - 當提問問題/ 285557和接受的答案時 –

回答

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 
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