+-------------+-------+
| Column Name | Type |
+-------------+-------+
| player_id | int |
| group_id | int |
+-------------+-------+
player_id is the primary key (column with unique values) of this table.
Each row of this table indicates the group of each player.
Table: Matches
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| match_id | int |
| first_player | int |
| second_player | int |
| first_score | int |
| second_score | int |
+---------------+---------+
match_id is the primary key (column with unique values) of this table.
Each row is a record of a match, first_player and second_player contain the player_id of each match.
first_score and second_score contain the number of points of the first_player and second_player respectively.
You may assume that, in each match, players belong to the same group.
The winner in each group is the player who scored the maximum total points within the group. In the case of a tie, the lowestplayer_id wins.
Write a solution to find the winner in each group.
WITH player_scores AS (
SELECT player_id,
SUM(score) AS total_score
FROM (
SELECT first_player AS player_id, first_score AS score FROM Matches
UNIONALLSELECT second_player AS player_id, second_score AS score FROM Matches
) t
GROUPBY player_id
)
SELECT p.group_id, p.player_id
FROM Players p
JOIN player_scores s ON p.player_id = s.player_id
WHERE (p.group_id, s.total_score, p.player_id) IN (
SELECT p2.group_id, MAX(s2.total_score), MIN(p2.player_id)
FROM Players p2
JOIN player_scores s2 ON p2.player_id = s2.player_id
GROUPBY p2.group_id
)
ORDERBY p.group_id;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
WITH player_scores AS (
SELECT player_id,
SUM(score) AS total_score
FROM (
SELECT first_player AS player_id, first_score AS score FROM Matches
UNIONALLSELECT second_player AS player_id, second_score AS score FROM Matches
) t
GROUPBY player_id
), ranked AS (
SELECT p.group_id, p.player_id, s.total_score,
RANK() OVER (PARTITION BY p.group_id ORDERBY s.total_score DESC, p.player_id ASC) as rnk
FROM Players p
JOIN player_scores s ON p.player_id = s.player_id
)
SELECT group_id, player_id
FROM ranked
WHERE rnk =1ORDERBY group_id;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
WITH player_scores AS (
SELECT player_id,
SUM(score) AS total_score
FROM (
SELECT first_player AS player_id, first_score AS score FROM Matches
UNIONALLSELECT second_player AS player_id, second_score AS score FROM Matches
)
GROUPBY player_id
), ranked AS (
SELECT p.group_id, p.player_id, s.total_score,
RANK() OVER (PARTITION BY p.group_id ORDERBY s.total_score DESC, p.player_id ASC) as rnk
FROM Players p
JOIN player_scores s ON p.player_id = s.player_id
)
SELECT group_id, player_id
FROM ranked
WHERE rnk =1ORDERBY group_id;