How can I get unique values of a varchar variable in oracle pl/sql? I have a variable like this:
aa;bb;aa;cc;dd;ee;dd
I would like to get the unique values still separated by ";". Desired result:
aa;bb;cc;dd;ee
Is this possible? Thanks.
How can I get unique values of a varchar variable in oracle pl/sql? I have a variable like this:
aa;bb;aa;cc;dd;ee;dd
I would like to get the unique values still separated by ";". Desired result:
aa;bb;cc;dd;ee
Is this possible? Thanks.
You can first split your string, use DISTINCT
to filter duplicates and combine it again using LISTAGG
(example at SQL Fiddle).
SELECT LISTAGG(x, ';') WITHIN GROUP(ORDER BY x)
FROM (
SELECT DISTINCT regexp_substr('aa;bb;aa;cc;dd;ee;dd', '[^;]+', 1, LEVEL) AS x
FROM dual
CONNECT BY regexp_substr('aa;bb;aa;cc;dd;ee;dd', '[^;]+', 1, LEVEL) IS NOT NULL
);
This returns
aa;bb;cc;dd;ee
In case of oracle 11g and greater you can use this
SELECT listagg(val,';') WITHin GROUP(ORDER BY NULL)
FROM
(SELECT DISTINCT REGEXP_SUBSTR('aa;bb;aa;cc;dd;ee;dd', '[^;]+', 1, LEVEL) val
FROM dual
CONNECT BY REGEXP_SUBSTR('aa;bb;aa;cc;dd;ee;dd', '[^;]+', 1, LEVEL) IS NOT NULL)
And xmlquery.
select xmlcast( xmlquery('let $i := string-join(distinct-values(ora:tokenize($doc,";")),";") return $i' passing 'aa;bb;aa;cc;dd;ee;dd' as "doc" returning content) as varchar2(4000)) from dual
You can easily achieve this by using REGEXP and WMSYS.WM_CONCAT(even though its undocumented function ) or LISTAGG to chive this. Please see below snippet. Hope this helps.
SELECT wm_concat(DISTINCT regexp_substr('aa;bb;aa;cc;dd;ee;dd','[^;]+', 1, level))
FROM dual
CONNECT BY regexp_substr('aa;bb;aa;cc;dd;ee;dd', '[^;]+', 1, level) IS NOT NULL;