HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Finding the partitions of a set which respect to some rules

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
thepartitionssomerespectfindingwhichrulesset

Problem

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      |
+--------+--------+

Solution

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)

Code Snippets

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)

Context

StackExchange Database Administrators Q#185410, answer score: 3

Revisions (0)

No revisions yet.