Question

I am using 11.2 version of oracle. I want to de-duplicate from LISTAGG.

below is existing data in oracle db:

Speaker | Qualification | Product
P           A              P1
P           B              P2
P           C              P3
P           D              P1
P           E              P2
Q           A              P1
Q           B              P2
Q           C              P1

Want below data:

Spkeaker | Product
P           ;P1;P2;P3;
Q           ;P1;P2;

Can any one help please.

Was it helpful?

Solution

select
  speaker,
  listagg(product, ';')
    within group (order by product)
    as products 
from
  (
    select distinct speaker, product
    from existing_data
  ) t
group by speaker
order by speaker ;

Test at: dbfiddle.uk

OTHER TIPS

In Oracle 19c, you can simply use DISTINCT:

SELECT Speaker, LISTAGG(DISTINCT Product, ';') Products
FROM datatable
GROUP BY Speaker

Add WITHIN GROUP ordering clause if needed.

fiddle


An important distinction made by ypercubeᵀᴹ

It seems that DISTINCT was added in LISTAGG only in the latest version 19c:

Oracle LiveSQL : 19C LISTAGG DISTINCT.

I generally use the following method to avoid creating subquery with DISTINCT values:

with CTE (Speaker, Qualification, Product) AS (
        SELECT 'P','A','P1' FROM DUAL UNION ALL
        SELECT 'P','B','P2' FROM DUAL UNION ALL
        SELECT 'P','C','P3' FROM DUAL UNION ALL
        SELECT 'P','D','P1' FROM DUAL UNION ALL
        SELECT 'P','E','P2' FROM DUAL UNION ALL
        SELECT 'Q','A','P1' FROM DUAL UNION ALL
        SELECT 'Q','B','P2' FROM DUAL UNION ALL
        SELECT 'Q','C','P1' FROM DUAL
    )
--
--ACTUAL QUERY STARTS FROM HERE
--
SELECT
    SPEAKER,
    ',' || REGEXP_REPLACE(RTRIM(XMLAGG(XMLELEMENT(E, PRODUCT, ',').EXTRACT('//text()')
        ORDER BY
            PRODUCT
    ).GETCLOBVAL(), ','), '([^,]+)(,\1)+', '\1') || ',' AS LIST
FROM
    CTE
GROUP BY
    SPEAKER;

Cheers!! -- Output --

S LIST                                                                            
- -------------
P ,P1,P2,P3,                                                                        
Q ,P1,P2,  
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top