题目介绍: 锦标赛优胜者 tournament-winners
难度困难
SQL架构
Players
玩家表
+-------------+-------+
| Column Name | Type |
+-------------+-------+
| player_id | int |
| group_id | int |
+-------------+-------+
玩家 ID 是此表的主键。
此表的每一行表示每个玩家的组。
Matches
赛事表
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| match_id | int |
| first_player | int |
| second_player | int |
| first_score | int |
| second_score | int |
+---------------+---------+
match_id 是此表的主键。
每一行是一场比赛的记录,第一名和第二名球员包含每场比赛的球员 ID。
第一个玩家和第二个玩家的分数分别包含第一个玩家和第二个玩家的分数。
你可以假设,在每一场比赛中,球员都属于同一组。
每组的获胜者是在组内得分最高的选手。如果平局,player_id 最小 的选手获胜。
编写一个 SQL 查询来查找每组中的获胜者。
查询结果格式如下所示
``` 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 表: +-----------+------------+ | group_id | player_id | +-----------+------------+ | 1 | 15 | | 2 | 35 | | 3 | 40 | +-----------+------------+ ```
union all
```sql 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 ```
sql
select group_id, player_id
from (
select players.*, sum(if(player_id = first_player, first_score, second_score)) score
from players join matches
on player_id = first_player or player_id = second_player
group by player_id
order by score desc, player_id
) tmp
group by group_id