Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the unique characters from a string in Oracle?

How to get the unique characters from a string in Oracle?

Lets say I have a column with data

CCCXXXCCCCCCCCCCCCCCCCXXCCCCCCCCCCCCCCCCCCCCCCC

and I want to return 'CX' as the list of unique characters.

likewise: aaaabbbccccdddaaa ==> abcd , HelloO ==> HeloO

Order is important, I want them to be in the same order as they first appear in the string.

Is there any way to do it without using stored procedure?

Edit: add more examples

like image 945
nandaka Avatar asked Jan 18 '23 21:01

nandaka


1 Answers

SELECT SUBSTR(REGEXP_SUBSTR('CCCCXXXCCCCCCCCCCCCCCCCXXCCCCCCCCCCCCCCCCCCCCCCC', '^(.)\1*.'), -2, 2) RESULT
FROM DUAL;

It returns CX

Here is another solution:

Select Replace (Wm_Concat (C), ',', '')
From
  (Select Substr ('CCCXCCCXXXCCCCCCCCCCCCCCCCXXCCCCCCCCCCCCCCCC', Rownum, 1) C,
    Min (Rownum) Rn
  From Dual
    Connect By Rownum <= Length ( 'CCCXCCCXXXCCCCCCCCCCCCCCCCXXCCCCCCCCCCCCCCCC')
  Group By Substr ( 'CCCXCCCXXXCCCCCCCCCCCCCCCCXXCCCCCCCCCCCCCCCC', Rownum, 1)
  Order By Rn
  ) X;

It returns all the unique chars in order of their occurence. Btw, yes, it looks horrible

like image 181
zerkms Avatar answered Jan 31 '23 01:01

zerkms