PostgreSQL组合没有重复

时间:2012-04-11 18:07:32

标签: sql postgresql math combinations

如何在postgres中使用字符串或数组并返回一些长度的所有组合?

例如,你有ABC,你想得到2个字符的组合,结果应该是:

AB AC BC

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:10)

set search_path='tmp';

WITH ztab AS (
SELECT idx as idx
, substring ( 'WTF!' FROM idx FOR 1) as str
FROM generate_series(1, char_length( 'WTF!' )) idx
)
SELECT t1.str, t2.str
FROM ztab t1
JOIN ztab t2 ON t2.idx > t1.idx
        ;

结果:

 str | str 
-----+-----
 W   | T
 W   | F
 W   | !
 T   | F
 T   | !
 F   | !
(6 rows)

不幸的是我找不到避免双字符串常量的方法。 (但整个事情可以打包成一个函数)如果没有重复的字符(或者你想要它们),你可以在str而不是idx上进行反连接。

UPDATE(来自ypercube的提示)看来OP希望连接字符串。所以吧::

WITH ztab AS (
SELECT idx as idx
, substring ( 'WTF!' FROM idx FOR 1) as str
FROM generate_series(1, char_length( 'WTF!' )) idx
)
SELECT t1.str || t2.str AS results
FROM ztab t1
JOIN ztab t2 ON t2.idx > t1.idx
        ;

结果:

 results 
---------
 WT
 WF
 W!
 TF
 T!
 F!
(6 rows)

UPDATE2 :(这是递归的东西......)

WITH RECURSIVE xtab AS (
        WITH no_cte AS (
        SELECT
        1::int AS len
        , idx as idx
        , substring ( 'WTF!' FROM idx FOR 1) as str
        FROM generate_series(1, char_length( 'WTF!' )) idx
        )
        SELECT t0.len as len
                , t0.idx
                , t0.str
        FROM no_cte t0
        UNION SELECT 1+t1.len
                , tc.idx
                , t1.str || tc.str AS str
        FROM xtab t1
        JOIN no_cte tc ON tc.idx > t1.idx
        )
SELECT * FROM xtab
ORDER BY len, str
-- WHERE len=2
        ;

结果3:

 len | idx | str  
-----+-----+------
   1 |   4 | !
   1 |   3 | F
   1 |   2 | T
   1 |   1 | W
   2 |   4 | F!
   2 |   4 | T!
   2 |   3 | TF
   2 |   4 | W!
   2 |   3 | WF
   2 |   2 | WT
   3 |   4 | TF!
   3 |   4 | WF!
   3 |   4 | WT!
   3 |   3 | WTF
   4 |   4 | WTF!
(15 rows)

答案 1 :(得分:1)

with chars as (
   select unnest(regexp_split_to_array('ABC','')) as c
)
select c1.c||c2.c
from chars c1
  cross join chars c2

要删除排列,您可以使用以下内容:

with chars as (
   select unnest(regexp_split_to_array('ABC','')) as c
)
select c1.c||c2.c
from chars c1
  cross join chars c2
where c1.c < c2.c

答案 2 :(得分:0)

如何使用多个单词...灵感来自@wildplasser和来自此来源info

WITH RECURSIVE xtab AS (
    WITH no_cte AS (
    SELECT
    1::int AS len
    , idx as idx
    , unnest(ARRAY['MY','POSTGRESQL','VERSION','9.6']) as str
    FROM generate_series(1, array_length(ARRAY['MY','POSTGRESQL','VERSION','9.6'],1)) idx
    )
    SELECT t0.len as len
            , t0.idx
            , t0.str
    FROM no_cte t0
    UNION SELECT 1+t1.len
            , tc.idx
            , t1.str ||','|| tc.str AS str
    FROM xtab t1
    JOIN no_cte tc ON tc.idx > t1.idx
    )
    SELECT distinct
    array_to_string(ARRAY(SELECT DISTINCT trim(x) FROM unnest(string_to_array(str,',')) x),', ') FROM xtab