下面的代码使用公共表表达式和
UNION ALL
. 数据是使用提供的查询和结果生成的。
DECLARE @Target TABLE (
[TargetListID] int,
[CustomFieldA] varchar(5),
[CustomFieldB] int,
[CustomFieldC] varchar(5),
[CustomFieldD] int
)
INSERT INTO @Target
VALUES
(1, 'TeamA', 1, 'TeamB', 2),
(1, 'TeamA', 1, 'TeamB', 2),
(1, 'TeamA', 1, 'TeamB', 2),
(1, 'TeamA', 1, 'TeamB', 2),
(1, 'TeamA', 1, 'TeamB', 2),
(1, 'TeamA', 1, 'TeamB', 2),
(1, 'TeamA', 1, 'TeamB', 2),
(1, 'TeamA', 1, 'TeamB', 2),
(1, 'TeamA', 1, 'TeamB', 2),
(1, 'TeamA', 1, 'TeamB', 2),
(1, 'TeamB', 2, 'TeamA', 1),
(1, 'TeamB', 2, 'TeamA', 1),
(1, 'TeamB', 2, 'TeamA', 1),
(1, 'TeamB', 2, 'TeamA', 1),
(1, 'TeamB', 2, 'TeamA', 1),
(1, 'TeamB', 2, 'TeamA', 1),
(1, 'TeamB', 2, 'TeamA', 1)
;WITH CTE AS (
SELECT
COUNT([CustomFieldA]) AS [Count],
[CustomFieldA] AS [Team1],
[CustomFieldB] AS [Team1Score],
[CustomFieldC] AS [Team2],
[CustomFieldD] AS [Team2Score]
FROM (
SELECT
[CustomFieldA],
[CustomFieldB],
[CustomFieldC],
[CustomFieldD]
FROM @Target
WHERE [TargetListID] = 1
) AS tbl
GROUP BY
[CustomFieldA],
[CustomFieldB],
[CustomFieldC],
[CustomFieldD]
)
SELECT
SUM([Count]) AS [Count],
Team1 AS Team,
Team1Score AS Score,
Team2 AS Team2,
Team2Score AS Score
FROM (
SELECT
CTE.[Count],
CTE.[Team1],
CTE.[Team1Score],
CTE.[Team2],
CTE.[Team2Score]
FROM CTE
WHERE CTE.[Team1Score] <= CTE.[Team2Score]
UNION ALL
SELECT
CTE.[Count],
CTE.[Team2],
CTE.[Team2Score],
CTE.[Team1],
CTE.[Team1Score]
FROM CTE
WHERE CTE.[Team2Score] < CTE.[Team1Score]
) AS U
GROUP BY
[Team1],
[Team1Score],
[Team2],
[Team2Score]
ORDER BY [Count] DESC
Count Team Score Team2 Score
----------- ----- ----------- ----- -----------
17 TeamA 1 TeamB 2