5

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

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

AB AC BC

预先感谢您的帮助。

4

3 回答 3

11
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 上做反连接。

更新(来自 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)
于 2012-04-11T18:41:12.853 回答
2
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
于 2012-04-11T21:00:30.703 回答
0

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

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
于 2017-03-14T18:42:36.503 回答