LeetCode:Database 66.锦标赛优胜者
Posted Xiao Miao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Database 66.锦标赛优胜者相关的知识,希望对你有一定的参考价值。
要求:编写一个 SQL 查询来查找每组中的获胜者。
每组的获胜者是在组内累积得分最高的选手。如果平局,player_id 最小 的选手获胜。
Players 玩家表的结构:
+-------------+-------+
| Column Name | Type |
+-------------+-------+
| player_id | int |
| group_id | int |
+-------------+-------+
player_id 是此表的主键。
此表的每一行表示每个玩家的组。
Matches 赛事表的结构:
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| match_id | int |
| first_player | int |
| second_player | int |
| first_score | int |
| second_score | int |
+---------------+---------+
match_id 是此表的主键。
每一行是一场比赛的记录,first_player 和 second_player 表示该场比赛的球员 ID。
first_score 和 second_score 分别表示 first_player 和 second_player 的得分。
你可以假设,在每一场比赛中,球员都属于同一组。
Players 表:
+-----------+------------+
| player_id | group_id |
+-----------+------------+
| 15 | 1 |
| 25 | 1 |
| 30 | 1 |
| 45 | 1 |
| 10 | 2 |
| 35 | 2 |
| 50 | 2 |
| 20 | 3 |
| 40 | 3 |
+-----------+------------+
Matches 表:
+------------+--------------+---------------+-------------+--------------+
| match_id | first_player | second_player | first_score | second_score |
+------------+--------------+---------------+-------------+--------------+
| 1 | 15 | 45 | 3 | 0 |
| 2 | 30 | 25 | 1 | 2 |
| 3 | 30 | 15 | 2 | 0 |
| 4 | 40 | 20 | 5 | 2 |
| 5 | 35 | 50 | 1 | 1 |
+------------+--------------+---------------+-------------+--------------+
Result Table:
+-----------+------------+
| group_id | player_id |
+-----------+------------+
| 1 | 15 |
| 2 | 35 |
| 3 | 40 |
+-----------+------------+
SQL语法:
WITH b AS (SELECT first_player,SUM(first_score) AS s1 FROM matches GROUP BY first_player)
, c AS (SELECT second_player,SUM(second_score) AS s2 FROM matches GROUP BY second_player)
select group_id,player_id from(
select group_id,player_id,num,row_number() over(partition by group_id order by num desc,player_id asc) as r from(
select a.player_id,a.group_id,(ifnull(b.s1,0)+ifnull(c.s2,0)) as num
from players a
left join b
on a.player_id=b.first_player
left join c
on c.second_player=a.player_id)d)e
where r=1;
以上是关于LeetCode:Database 66.锦标赛优胜者的主要内容,如果未能解决你的问题,请参考以下文章
数据结构与算法之深入解析最优运动员比拼回合的求解思路与算法示例