简体   繁体   English

oracle中不同的listagg

[英]distinct listagg in oracle

I have a query something like this: 我有这样的查询:

select tab1.id,
(
select listagg(tab2.surna||'  '||tab2.name||':'||tab2.addr||'  '||tab2.numb,',  ') within group( order by tab2.name)
from tab2
where tab1.id=tab2.id2id  /*join tab1 with tab2 */
)as address
from tab1

and the result is like: 结果是:

name_surname1:addr 1,name_surname1:addr 2,name_surname2:addr 3 name_surname1:addr 1,name_surname1:addr 2,name_surname2:addr 3

but the exptected result would be something like: 但预期的结果是:

name_surname1:(addr 1,addr 2),name_surname2:(addr 3) name_surname1 :(地址1,addr 2),name_surname2 :(地址3)

how can i implement this in order to avoid duplicate records in the display names? 为了避免显示名称重复记录,我该如何实现?

Thanks 谢谢

I think you need 2 levels of listagg for that. 我认为您需要2个级别的listagg As you didn't provide any script to replicate your data structure, I provide a generic example of my own... 由于您未提供任何脚本来复制您的数据结构,因此我提供了自己的通用示例...

with tab as (
select 's' s,'n' n, 'addr1' addr from dual
union all
select 's' s,'n' n, 'addr2' addr from dual
union all
select 'd' s,'k' n, 'addr3' addr from dual
union all
select 'd' s,'k' n, 'addr4' addr from dual
)
select listagg(res,',') within group (order by res) final_res from ( 
select s || n || ':(' ||listagg( addr,',  ')  within group (order by s,n)  || ')'res  
from tab  
group by s||n
) 

result is 结果是

dk:(addr3, addr4),sn:(addr1, addr2)

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

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