Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL and unique n-column combinations

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?

like image 711
ough Avatar asked May 07 '11 21:05

ough


1 Answers

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.

like image 162
Andriy M Avatar answered Oct 04 '22 15:10

Andriy M