0

我有一个这样的查询:

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

结果是这样的:

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

但预期的结果是这样的:

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

我该如何实现这一点以避免显示名称中的重复记录?

谢谢

4

1 回答 1

4

我认为你需要2个级别listagg。由于您没有提供任何脚本来复制您的数据结构,我提供了一个我自己的通用示例......

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
) 

结果是

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

于 2016-09-07T08:50:32.790 回答