De-Duplicate from LISTAGG
-
07-02-2021 - |
Frage
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.
Lösung
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
Andere Tipps
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.
An important distinction made by ypercubeᵀᴹ
It seems that DISTINCT was added in LISTAGG only in the latest version 19c:
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,
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit dba.stackexchange