如何从Oracle中的字符串中获取唯一字符?

vfwfrxfs  于 2023-10-16  发布在  Oracle
关注(0)|答案(2)|浏览(122)

如何从Oracle中的字符串中获取唯一字符?
假设我有一个包含数据的列

CCCXXXCCCCCCCCCCCCCCCCXXCCCCCCCCCCCCCCCCCCCCCCC

我想返回'CX'作为唯一字符的列表。
同样:aaaabbbccccdddaaa ==> abcd,HelloO ==> HeloO
顺序很重要,我希望它们的顺序与它们第一次出现在字符串中的顺序相同。
有没有什么方法可以不使用存储过程呢?
编辑:添加更多示例

41zrol4v

41zrol4v1#

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

返回CX
这是另一个解决方案:

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;

它按出现的顺序返回所有唯一的字符。顺便说一句,是的,它看起来很可怕

xsuvu9jc

xsuvu9jc2#

其他适合我的解决方案:

-- First, create a custom collection type (nested table type) to hold the unique characters:
CREATE OR REPLACE TYPE char_list AS TABLE OF VARCHAR2(1);

-- Next, create a pipelined function that splits the input string into unique characters and returns them as a collection:
CREATE OR REPLACE FUNCTION split_string(input_string VARCHAR2) RETURN char_list PIPELINED IS
BEGIN
    FOR i IN 1..LENGTH(input_string) LOOP
        PIPE ROW (SUBSTR(input_string, i, 1));
    END LOOP;
    RETURN;
END split_string;
/

-- Finally, use the pipelined function to list the unique characters in a string:
SELECT DISTINCT COLUMN_VALUE AS unique_character
FROM TABLE(split_string('YourInputStringToBeOrNotToBe'))
ORDER BY 1;

相关问题