I have
POW,POW,POWPRO,PRO,PRO,PROUTL,TNEUTL,TNEUTL,UTL,UTLTNE,UTL,UTLTNE
I want
POW,POWPRO,PRO,PROUTL,TNEUTL,UTL,UTLTNE
I tried
select regexp_replace('POW,POW,POWPRO,PRO,PRO,PROUTL,TNEUTL,TNEUTL,UTL,UTLTNE,UTL,UTLTNE','([^,]+)(,\1)+','\1') from dual
And I get the output
POWPROUTL,TNEUTL,UTLTNE,UTLTNE
But i want the output to be
POW,POWPRO,PRO,PROUTL,TNEUTL,UTL,UTLTNE
Please help.
Two solutions that use only SQL and a third solution that uses a small/simple PL/SQL function which makes for a very short final SQL query.
Oracle Setup:
Query 1:
Outputs:
Query 2:
Output:
Oracle Setup:
A small helper function:
Query 3:
or (if you only want to pass a single value):
Output:
The solution offered below uses straight SQL (no PL/SQL). It works with any possible input string, and it removes duplicates in place - it keeps the order of input tokens, whatever that order is. It also removes consecutive commas (it "deletes nulls" from the input string) while treating null inputs correctly. Notice the output for an input string consisting of commas only, and the correct treatment of "tokens" consisting of two spaces and one space respectively.
The query runs relatively slowly; if performance is an issue, it can be re-written as a recursive query, using "traditional"
substr
andinstr
which are quite a bit faster than regular expressions.Results for the inputs I created: