Finding the partitions of a set which respect to some rules Assume the following table. I want to partition it in a way that it never happens to have elements from Field1 and Field2 which are "connected" (i.e. a and 1, a and 2, b and 1) go to a separate partition.

This is the solution with 3 partitions.

ab12, c3, d45


+--------+--------+
| Field1 | Field2 |
+--------+--------+
| a      | 1      |
+--------+--------+
| a      | 2      |
+--------+--------+
| b      | 1      |
+--------+--------+
| b      | 2      |
+--------+--------+
| c      | 3      |
+--------+--------+
| d      | 4      |
+--------+--------+
| d      | 5      |
+--------+--------+
Using 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;


Result:

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