Partitioning

查找符合某些規則的集合的分區

  • September 8, 2017

假設下表。我想以這樣一種方式對其進行分區,即它永遠不會讓來自 Field1 和 Field2 的元素“連接”(即 a 和 1、a 和 2、b 和 1)進入單獨的分區。

這是具有 3 個分區的解決方案。

ab12, c3, d45


+--------+--------+
| Field1 | Field2 |
+--------+--------+
| a      | 1      |
+--------+--------+
| a      | 2      |
+--------+--------+
| b      | 1      |
+--------+--------+
| b      | 2      |
+--------+--------+
| c      | 3      |
+--------+--------+
| d      | 4      |
+--------+--------+
| d      | 5      |
+--------+--------+

使用 PostgreSQL

WITH t AS (
       SELECT f1, array_agg(f2) AS p
       FROM (
               VALUES
                ( 'a',1 ),
                ( 'a',2 ),
                ( 'b',1 ),
                ( 'b',2 ),
                ( 'c',3 ),
                ( 'd',4 ),
                ( 'd',5 )
       ) AS t(f1,f2)
       GROUP BY f1
)
SELECT array_to_string(p1, '') || array_to_string(p2, '') AS partitions
FROM (
       SELECT array_agg(DISTINCT t2.f1) AS p1, p AS p2
       FROM t AS t1
       INNER JOIN t AS t2 USING (p)
       GROUP BY p
) AS t;

結果:

partitions 
------------
ab12
c3
d45
(3 rows)

引用自:https://dba.stackexchange.com/questions/185410