PostgreSQL组合与排列不同

时间:2015-05-27 00:16:07

标签: sql arrays postgresql combinations permutation

无法弄清楚如何在不重复的情况下组合数组。

   INPUT is an array of n variables LIKE '{A,B,C,D,E}'
   Variable A is always single array LIKE '{"A"}' or '{"D,C"}' or '{"D,A,B"}' etc..

   What I need is to combine INPUT with A(i)

 EXAMPLE:
     1. A = '{"B"}'       --> att='{"B,A","B,C","B,D","B,E"}'
     2. A = '{"B,C"}'     --> att='{"B,C,A","B,C,D","B,C,E"}'
     3. A = '{"B,C,A"}'   --> att='{"B,C,A,D","B,C,A,E"}'
     4. A = '{"B,C,A,D"}' --> att='{"B,C,A,D,E"}'

到目前为止,我有这个:

WITH A(i) AS (SELECT * FROM unnest(ARRAY['A,B'])),
     B(j) AS (SELECT * FROM unnest(ARRAY['A','B','C','D'])),

     cte AS ( SELECT A.i ||','|| B.j
              FROM A
              CROSS JOIN   B 
            )
     SELECT ARRAY ( SELECT * FROM cte) INTO att;

但这会造成两面性:

"{"A,B,A","A,B,B","A,B,C","A,B,D"}"

1 个答案:

答案 0 :(得分:0)

WITH  RECURSIVE 

     A(i) AS (SELECT * FROM unnest(ARRAY['A,B'])),
     B(j) AS (SELECT * FROM unnest(ARRAY['A','B','C','D'])),

     cte AS (  SELECT j AS combo, j, 1 AS ct 
               FROM B 
             UNION ALL 
               SELECT cte.combo ||','||B.j, B.j, ct + 1 
               FROM cte, B
               WHERE ct <= 4
                AND position(B.j in cte.combo) = 0
            )
    , com AS ( SELECT A.i ||','|| B.j AS cmb
               FROM A
               CROSS JOIN B)

     SELECT ARRAY(SELECT cmb FROM cte,com where cte.combo = com.cmb)