Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a permutations or combinations of n rows in m columns?

Tags:

Does anyone know how to create a table with m columns from table of n rows where the values in columns of each row represent a different combination or permutation of values from the original table?

For example the original table has 1 column (number_value) with 3 (n=3) rows:

1 2 3 

The table which contains combinations (the order doesn't matter) of two values (m = 2) would be the following:

number1, number2 1,2 1,3 2,3 

and the table of permutations would be the following:

number1, number2 1, 2 2, 1 1, 3 3, 1 2, 3 3, 2 

The order of rows doesn't matter.

Thank you in advance!

like image 380
Niko Gamulin Avatar asked Nov 11 '10 21:11

Niko Gamulin


People also ask

How do I get unique combinations in SQL?

Simply use the DISTINCT keyword: SELECT DISTINCT Latitude, Longitude FROM Coordinates; This will return values where the (Latitude, Longitude) combination is unique.

How do you do number combinations?

In fact, if you know the number of combinations, you can easily calculate the number of permutations: P(n,r) = C(n,r) * r! . If you switch on the advanced mode of this combination calculator, you will be able to find the number of permutations.


1 Answers

Combinations:

SELECT T1.x, T2.x FROM your_table T1 JOIN your_table T2 ON T1.x < T2.x 

Permutations:

SELECT T1.x, T2.x FROM your_table T1 JOIN your_table T2 ON T1.x != T2.x 

I am assuming that the values in the original table are unique.

To generalize for larger values of m you need to add more joins.

like image 126
Mark Byers Avatar answered Nov 16 '22 22:11

Mark Byers