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:
For 3 columns you would then need to make some additions (highlighted in bold):
I’m sure you can now easily guess how to scale this for more columns.