看到,因爲沒有其他人給了這個答案,我想我也可以告訴你一個使用動態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次(取決於是否有偶數或奇數的球隊)。
來源
2017-04-18 05:05:41
ZLK