Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : generate possible combinations of numbers

I have a total universe of 41 numbers, and I'm trying to generate the possible combinations of 6 digits between these numbers and insert them into a table in SQL Server.

Could anyone give me a help to do this?

Thank you very much!

like image 853
Isaias Peña Cromilakis Avatar asked Jun 21 '15 22:06

Isaias Peña Cromilakis


People also ask

How do you generate all possible combinations of one list?

Enter the formula =List1. Expand out the new List1 column and then Close & Load the query to a table. The table will have all the combinations of items from both lists and we saved on making a custom column in List1 and avoided using a merge query altogether!


2 Answers

To generate all possible permutations (41!/(6!*(41-6)!) is just under 4.5 million) you could use

WITH Balls(N)
     AS (SELECT number
         FROM  master..spt_values
         WHERE type='P'
         AND number BETWEEN 1 AND 41)
SELECT *
FROM   Balls B1
       JOIN Balls B2
         ON B2.N > B1.N
       JOIN Balls B3
         ON B3.N > B2.N
       JOIN Balls B4
         ON B4.N > B3.N
       JOIN Balls B5
         ON B5.N > B4.N
       JOIN Balls B6
         ON B6.N > B5.N 

enter image description here

like image 118
Martin Smith Avatar answered Sep 28 '22 00:09

Martin Smith


Store the numbers in a table, and use cross join six times to match this table with itself. If numbers cannot repeat, add where clauses, or inner join with on clause like on t3.num not in (t1.num,t2.num)

drop table #temp
GO
create table #temp (num int identity(1,1), x int)
GO
insert into #temp default values
GO 41

select 
    *
from #temp t1
cross join #temp t2
cross join #temp t3 
-- and so on
like image 20
AdamL Avatar answered Sep 28 '22 00:09

AdamL