SELECT * FROM test; a | b ---+--- 1 | 5 4 | 1 2 | 5 3 | 3 1 | 1 (5 rows)
How can i write such query, so all output values in “a” column are distinct and all output values in “b” column are also distinct.
So, for example, valid result set for above query is:
1 | 5 4 | 1 3 | 3
Next one is also valid:
4 | 1 2 | 5 3 | 3
It is better to find as many results as possible, but it’s not a requirement.
What is the best way to do that ?
Thanks.
Found solution myself! 🙂
a) add id column to “test” table
b) sql query:
WITH t1 AS ( SELECT a, MIN(id) as id FROM test GROUP BY a ), t2 AS ( SELECT b, MIN(id) as id FROM test GROUP BY b ) SELECT * FROM test WHERE id IN ( SELECT id FROM t1 ) AND id IN ( SELECT id FROM t2 );Result: