SQL - Need to group data by 2 different columns
I know that the question sounds like this is going to be an easy question, but let me explain. I have a result set where I get
Count Team Score Team2 Score
-----------------------------------------
10 TeamA 1 TeamB 2
7 TeamB 2 TeamA 1
Now, because I have the same result, but the Teams are in different columns I get the 2 results. 开发者_如何学编程 I am looking for a way of retrieving the one result like so:
Count Team Score Team2 Score
-----------------------------------------
17 TeamA 1 TeamB 2
Is this possible?
EDIT
SELECT TOP 5 SUM([CountryCount]) AS [CountryCount]
,[Country], [CustomFieldB], [CustomFieldC], [CustomFieldD]
FROM (
SELECT COUNT([Country]) AS [CountryCount], [CustomFieldB], [CustomFieldC], [CustomFieldD]
,[Country]
FROM (
SELECT [CustomFieldA] AS [Country], [CustomFieldB], [CustomFieldC], [CustomFieldD]
FROM [Target]
WHERE [TargetListID] = xxx
) as tbl
GROUP
BY [Country], [CustomFieldB], [CustomFieldC], [CustomFieldD]
) as T
GROUP
BY [Country], [CustomFieldB], [CustomFieldC], [CustomFieldD]
ORDER
BY [CountryCount] DESC;
The following code accomplishes the desired results using a Common Table Expression and a UNION ALL
. The data was made up using the query and results provided.
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
This query gives the desired result.
Count Team Score Team2 Score
----------- ----- ----------- ----- -----------
17 TeamA 1 TeamB 2
精彩评论