因为这使用了一些循环和表变量,所以对于大型集合来说,它不是最有效的解决方案。但是,如果您只对 16 个团队执行一次此操作,则可以:
create table Teams (team varchar(5))
insert into Teams(team) values
('a'),
('b'),
('c'),
('d'),
('e'),
('f'),
('g'),
('h'),
('i'),
('j'),
('k'),
('l'),
('m'),
('n'),
('o'),
('p')
使用独占交叉连接来创建独特的对决:
declare @Matchups table (home varchar(5), away varchar(5), orderNo float)
insert into @Matchups
select * from (
select x1.team as home, x2.team as away,RAND(CHECKSUM(NEWID())) as orderNo from @x x1
cross join @x x2
where x1.tm <> x2.tm
) a
declare @half1 table (home varchar(5), away varchar(5), week int)
declare @matchup int = 15
declare @week int = 15
创建第一场比赛,然后在表格中循环,确保没有球队在同一周比赛两次并且没有重复比赛
delete top(1) from @Matchups
output deleted.home,deleted.away,@week into @half1
set @matchup = @matchup - 1
while @week > 0
begin
while @matchup > 0
begin
delete top(1) s
output deleted.home,deleted.away,@week into @half1
from @Matchups s
where not exists (
select 1 from @half1 m
where ((m.away = s.away
or m.away = s.home
or m.home = s.away
or m.home = s.home)
and week = @week)
or
(m.away = s.away
and m.home = s.home)
or
(m.away = s.home
and m.home = s.away)
)
set @matchup = @matchup - 1
end
set @week = @week - 1
set @matchup = 15
end
set @week = 15
set @matchup = 8
对于下半场,只需以相反的主客场顺序将值插入表中,然后随机化比赛。
declare @half2 table (home varchar(5), away varchar(5), week int)
while @week > 0
begin
while @matchup > 0
begin
insert into @half2
select top 1 away,home,@week from
(select *,RAND(CHECKSUM(NEWID())) as orderNo from @half1 h1
where not exists (
select 1 from @half2 h2
where (h1.away = h2.away
or h1.away = h2.home
or h1.home = h2.away
or h1.home = h2.home)
and week = @week)) a
order by orderNo
set @matchup = @matchup - 1
end
set @matchup = 8
set @week = @week - 1
end
select *,1 as Half from @half1
union all
select *,2 as Half from @half2