LeetCode(数据库)- 锦标赛优胜者

Posted 程序员牧码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(数据库)- 锦标赛优胜者相关的知识,希望对你有一定的参考价值。

题目链接:点击打开链接

题目大意:略。

解题思路:解决方案(1) 最后只需要再使用一次 FROM 子句和 GROUP BY 取出每个组的第一条数据即可。

AC 代码

-- 解决方案(1)
SELECT group_id, player_id
FROM (
    SELECT group_id, player_id, SUM(score) AS score
    FROM (
        -- 每个用户总的 first_score
        SELECT Players.group_id, Players.player_id, SUM(Matches.first_score) AS score
        FROM Players JOIN Matches ON Players.player_id = Matches.first_player
        GROUP BY Players.player_id

        UNION ALL

        -- 每个用户总的 second_score
        SELECT Players.group_id, Players.player_id, SUM(Matches.second_score) AS score
        FROM Players JOIN Matches ON Players.player_id = Matches.second_player
        GROUP BY Players.player_id
    ) s
    GROUP BY player_id
    ORDER BY score DESC, player_id
) result
GROUP BY group_id

-- 解决方案(2)
WITH t1 AS(SELECT player, SUM(score) sumn
FROM (
SELECT first_player player, first_score score FROM Matches
UNION ALL
SELECT second_player, second_score FROM Matches
) t
GROUP BY player),

t2 AS(SELECT group_id, player player_id, ROW_NUMBER() OVER(PARTITION BY group_id ORDER BY sumn DESC, player) rw
FROM Players p JOIN t1 ON p.player_id = t1.player)

SELECT group_id, player_id 
FROM t2
WHERE rw = 1

以上是关于LeetCode(数据库)- 锦标赛优胜者的主要内容,如果未能解决你的问题,请参考以下文章

代码赏析——满二叉树

算法-排序锦标赛排序

为锦标赛系统分配奖品

锦标赛

在锦标赛中可能获胜的算法

如何可靠地进行 API 调用?