在SQL中选择不在当前表中的数字组合

时间:2018-07-09 14:02:16

标签: sql sql-server

我有一个5列的表格。 该表如下所示:

Col1 Col2 Col3 Col4 Col5
7    12   15   24   39
10   11   27   30   36
1    10   15   22   32
3    18   19   20   40
6    16   21   24   31

我需要找到当前表中没有的1到40之间的所有组合。

我如何完成此任务?

非常感谢!

1 个答案:

答案 0 :(得分:0)

据我所知,这是必需的:找到5个未重复的数字(小于40)的所有组合(不在现有列表中)。

Create table [AllCombinations] (col1 int, col2 int, col3 int, col4 int, col5 int)

declare @loop1 int = 1
declare @loop2 int = 1
declare @loop3 int = 1
declare @loop4 int = 1
declare @loop5 int = 1

declare @topnum int = 40

while @loop1 <= @topnum
    begin
    set @loop2 = @loop1 + 1
    while @loop2 <= @topnum
        begin
        set @loop3 = @loop2 + 1
        while @loop3 <= @topnum
            begin
            set @loop4 = @loop3 + 1
            while @loop4 <= @topnum
                begin
                set @loop5 = @loop4 + 1
                while @loop5 <= @topnum
                    begin
                    Insert into [AllCombinations] values(@loop1, @loop2, @loop3, @loop4, @loop5) 
                    --print cast(@loop1 as char(2)) + ', ' + cast(@loop2 as char(2)) + ', ' + cast(@loop3 as char(2)) + ', ' + cast(@loop4 as char(2)) + ', ' + cast(@loop5 as char(2))
                    set @loop5 = @loop5 + 1
                    end
                set @loop4 = @loop4 + 1
                end
            set @loop3 = @loop3 + 1
            end
        set @loop2 = @loop2 + 1
        end
    set @loop1 = @loop1 + 1
    end

Create table [MyNumbers] (col1 int, col2 int, col3 int, col4 int, col5 int)
insert into [MyNumbers] values 
  (7 , 12, 15, 24, 39)
, (10, 11, 27, 30, 36)
, (1 , 10, 15, 22, 32)
, (3 , 18, 19, 20, 40)
, (6 , 16, 21, 24, 31)

select * from AllCombinations
except
select * from mynumbers