Anastasis Anastasis - 2 months ago 23
SQL Question

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

but the exptected result would be something like:

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

how can i implement this in order to avoid duplicate records in the display names?

Thanks

Answer

I think you need 2 levels of listagg for that. 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)

Comments