Is there a simple way on Oracle to query unique combinations of n fields. I Have very simple two-field solution:
CREATE TABLE combinations AS
SELECT 1 AS n
FROM DUAL
UNION ALL
SELECT 2
FROM DUAL;
Querying for unique combinations:
SELECT LEAST(x.a, x.b),
GREATEST(x.a,x.b)
FROM (SELECT c1.n a,
c2.n b
FROM combinations c1
CROSS JOIN combinations c2
WHERE c1.n <> c2.n) x
GROUP BY LEAST(x.a, x.b), GREATEST(x.a,x.b);
From this query 1,2 and 2,1 are considered the same. Unfortunately it doesn't work for 3-field structure (for example 1,2,3 must be considered the same as 3,1,2 because ordering of values doesn't matter). Does Oracle analytic functions provide appropriate solution for this question? Could you suggest some particular Oracle analytic function?
Your query for 2 columns could be rewritten like this:
SELECT
c1.n,
c2.n
FROM combinations c1
INNER JOIN combinations c2 ON c1.n < c2.n
For 3 columns you would then need to make some additions (highlighted in bold):
SELECT
c1.n,
c2.n,
c3.n
FROM combinations c1
INNER JOIN combinations c2 ON c1.n < c2.n
INNER JOIN combinations c3 ON c2.n < c3.n
I'm sure you can now easily guess how to scale this for more columns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With