sql总和按多列分组

时间:2019-06-03 14:11:55

标签: sql sql-server

我正在尝试为游戏锦标赛打分。有多个锦标赛,每个团队都有两名玩家,玩家1和玩家2。注册时,任何一个玩家都可以处于玩家1或玩家2的位置。每当两个相同的玩家组队在一起时,我需要总结一下整个锦标赛所获得的积分。

Tournament_ID|Player1|Player2|Points
------------------------------------
1            |Smith  |Green  |8
1            |Brown  |Peck   |3
1            |Jones  |Healy  |2

2            |Smith  |Green  |5
2            |Peck   |Brown  |3
2            |Jones  |Healy  |1

3            |Healy  |Jones  |9
3            |Smith  |Green  |5
3            |Peck   |Brown  |3

结果应如下所示:

Place  Team              Total Points
1      Smith & Green        18
2      Jones & Healy        12
3      Brown & Peck          9

1 个答案:

答案 0 :(得分:4)

这是一种方法:

WITH cte AS (
    SELECT
        CASE WHEN Player1 < Player2 THEN Player1 ELSE Player2 END AS Player1,
        CASE WHEN Player1 < Player2 THEN Player2 ELSE Player1 END AS Player2,
        Points
    FROM yourTable
)

SELECT
    ROW_NUMBER() OVER (ORDER BY SUM(Points) DESC) Place,
    Player1 + ' & ' + Player2,
    SUM(Points) AS [Total Points]
FROM cte
GROUP BY
    Player1 + ' & ' + Player2;

enter image description here

Demo