Question:

We have a table named teams. We need to create a schedule for the teams ensure 
1)      they can play with another team in each round.
2)      Every team should play in every round.
3)      Each team should play with every other team twice (once as Host_Team and once as Guest_Team) 
TeamID TeamName
1              A
2              B
3              C
4              D

Expected results: three columns
Round  Host_Team Guest_team
1              A                     B
1              C                     D
2              A                     C
2              B                     D
3               A                     D
3               C                     B
4               B                     C
4               D                    A
5               B                     A
5               D                     C
6               C                     A
6                D                   B
IF OBJECT_ID('teams','U') IS NOT NULL
  DROP TABLE teams
GO

CREATE TABLE teams(  
       TeamID INT,
       TeamName VARCHAR(50)
)
GO
INSERT INTO teams(TeamID,TeamName)
SELECT 1,'A' UNION ALL  
SELECT 2,'B' UNION ALL  
SELECT 3,'C' UNION ALL
SELECT 4,'D'

SELECT * FROM teams

hard code Solution

WITH temp 
     AS (SELECT a.teamid   AS aID, 
                a.teamname AName, 
                b.teamname, 
                CASE 
                  WHEN ( a.teamid + b.teamid ) > 5 THEN 10 - ( 
                  a.teamid + b.teamid ) 
                  ELSE ( a.teamid + b.teamid ) 
                END        AS od, 
                CASE 
                  WHEN ( a.teamid - b.teamid ) > 0 THEN 1 
                  ELSE 0 
                END        AS part 
         FROM   teams a, 
                teams b 
         WHERE  a.teamname < b.teamname 
                 OR a.teamname > b.teamname) 
SELECT Ntile(6) 
         OVER( 
           ORDER BY temp.part, temp.od ) AS Rounds, 
       temp.aname                        AS Host_Team, 
       temp.teamname                     AS Guest_team 
FROM   temp 
ORDER  BY temp.part, 
          temp.od, 
          temp.aid 

 Improved Solution (works for more teams)

with test as 
(
select t.TeamID,t.TeamName,count(1) over (partition by 1) as CNT
from teams  t
)
select t1.TeamID,t2.TeamID,t1.CNT,case when t2.TeamID=t1.CNT then (t1.TeamID*2-1)%t1.CNT+(t1.TeamID*2-1)/t1.CNT
            when t1.TeamID=t1.CNT then (t2.TeamID*2-1)%t1.CNT+(t2.TeamID*2-1)/t1.CNT
			else (t1.TeamID+t2.TeamID-2)%(t1.CNT-1)+1
			end +case when t1.TeamID>t2.TeamID then t1.CNT-1 else 0 end part
			
			 ,t1.TeamName as h
			,t2.TeamName as a 
from test t1
join test t2 on t1.TeamID<>t2.TeamID 
order by part,t1.TeamName,t2.TeamName

 

 

 posted on 2013-04-12 11:34  julianlin  阅读(105)  评论(0)    收藏  举报