2017-04-17 65 views
0

我需要一個表格,其名稱爲偶數個團隊,並且這些表格會生成一個錦標賽的時間表,即如果有4個團隊:team1,team2,team3和team4該表的名稱,那麼結果表看起來像下面的在SQL Server中生成錦標賽賽程表

Team Team  Round 
----------------------- 
team1 team2 1 
team 3 team4 1 
team1 team3 2 
team2 team4 2 
team1 team4 3 
team2 team3 3 

我需要使用T-SQL來做到這一點。我曾嘗試使用Round Robin Tournament算法,但我不知道如何在T-SQL中實現它。

回答

0

看到,因爲沒有其他人給了這個答案,我想我也可以告訴你一個使用動態SQL這樣的(可能是低效的)方式:

DECLARE @SQL NVARCHAR(MAX) = N''; 
SELECT TOP (SELECT CASE COUNT(*) % 2 WHEN 1 THEN COUNT(*) ELSE COUNT(*) - 1 END FROM dbo.Teams) @SQL += N' UNION ALL 
SELECT * 
FROM 
(
    SELECT TOP (SELECT COUNT(*)/2 FROM T) 
     Team, 
     RN, 
     RoundNum = ' + CAST(N AS NVARCHAR(3)) + N', 
     Match = ROW_NUMBER() OVER (ORDER BY CASE WHEN RN = 1 THEN 0 ELSE 1 END, (RN + ' + CAST(N - 2 AS NVARCHAR(3)) + N') % (SELECT COUNT(*) FROM T)), 
     Slot = 1 
    FROM T 
    ORDER BY CASE WHEN RN = 1 THEN 0 ELSE 1 END, (RN + ' + CAST(N - 2 AS NVARCHAR(3)) + N') % (SELECT COUNT(*) FROM T) 
    UNION ALL 
    SELECT TOP (SELECT COUNT(*)/2 FROM T) 
     Team, 
     RN, 
     RoundNum = ' + CAST(N AS NVARCHAR(3)) + N', 
     Match = ROW_NUMBER() OVER (ORDER BY CASE WHEN RN = 1 THEN 1 ELSE 0 END, (RN + ' + CAST(N - 2 AS NVARCHAR(3)) + N') % (SELECT COUNT(*) FROM T) DESC), 
     Slot = 2 
    FROM T 
    ORDER BY CASE WHEN RN = 1 THEN 1 ELSE 0 END, (RN + ' + CAST(N - 2 AS NVARCHAR(3)) + N') % (SELECT COUNT(*) FROM T) DESC 
) AS T 
' 
FROM (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM sys.objects) T(N) 
ORDER BY N; 

SELECT @SQL = N' 
WITH T AS 
(
    SELECT Team, RN = ROW_NUMBER() OVER (ORDER BY Team) 
    FROM dbo.Teams 
    UNION ALL 
    SELECT ''Bye'', COUNT(*) + 1 
    FROM dbo.Teams 
    HAVING COUNT(*) % 2 = 1 
), 
CTE2 AS 
(
' + STUFF(@SQL, 1, 11, '') + N' 
) 
SELECT T1.RoundNum, T1.Match, Team1 = T1.Team, Team2 = T2.Team 
FROM 
(
    SELECT * 
    FROM CTE2 
    WHERE Slot = 1 
) AS T1 JOIN 
(
    SELECT * 
    FROM CTE2 
    WHERE Slot = 2 
) AS T2 
    ON T2.RoundNum = T1.RoundNum 
    AND T2.Match = T1.Match;'; 


EXEC sp_executesql @SQL; 

從本質上講,它的fix one of the contributors in the first or last column of the table描述在你的維基鏈接中,通過紮根1並將所有團隊轉移到1左右。對於奇數團隊,它會添加一個「再見」對手。而且它只是在表格中循環N或N-1次(取決於是否有偶數或奇數的球隊)。