Oracle - 字符串组合排列

时间:2011-08-02 18:49:43

标签: sql oracle plsql oracle10g

我认为我有一个复杂的要求。

这是使用Oracle 10.2的组合排列,我能够使用笛卡尔连接来解决它,但我认为它需要一些改进才能使其最简单,更灵活。

主要行为。

输入字符串:'一二'

输出: '一' '二' '一二' '两个'

对于我的解决方案,我已将字符串数量限制为5(请注意,输出是靠近阶乘的数字)

SQL:

with My_Input_String as (select 1 as str_id, 'alpha beta omega gama' as str from dual )

--------logic-------

, String_Parse as (
                    SELECT REGEXP_SUBSTR(str, '[^ ]+', 1, ROWNUM) str
                    FROM My_Input_String
                    where rownum < 6 -- string limitation --
                    CONNECT BY level <= LENGTH(REGEXP_REPLACE(str, '([^ ])+|.', '\1') ) 
                  )    

--------CRAP select need refactoring-------

select str from String_Parse
union
select  REGEXP_REPLACE(trim(s1.str||' '||s2.str||' '||s3.str||' '||s4.str||' '||s5.str), '( ){2,}', ' ') as str
from 

(select str from String_Parse union select ' ' from dual) s1,
(select str from String_Parse union select '  ' from dual) s2,
(select str from String_Parse union select '   ' from dual) s3,
(select str from String_Parse union select '    ' from dual) s4,
(select str from String_Parse union select '     ' from dual) s5
where 
--
s1.str <> s2.str and s1.str <> s3.str and s1.str <> s4.str and s1.str <> s5.str
--
and s2.str <> s3.str and s2.str <> s4.str and s2.str <> s5.str
--
and s3.str <> s4.str and s3.str <> s5.str
--
and s4.str <> s5.str

1 个答案:

答案 0 :(得分:9)

编辑:得到通用的。最后真的很简单(但我花了一些时间才到达那里)

WITH words AS
(   SELECT  REGEXP_SUBSTR( '&txt', '\S+', 1, LEVEL )    AS word
        ,   LEVEL                                       AS num
    FROM    DUAL
    CONNECT BY LEVEL <= LENGTH( REGEXP_REPLACE( '&txt', '\S+\s*', 'X' ) )
)
SELECT  SYS_CONNECT_BY_PATH( W.word, ' ' )
FROM    words   W
CONNECT BY NOCYCLE PRIOR W.num != W.num

Edit2:删除了多余的maxnum内容。遗留下来的尝试