Grand Slam Titles Problem
Description
LeetCode Problem 1783.
Table: Players
1
2
3
4
5
6
7
8
+----------------+---------+
| Column Name | Type |
+----------------+---------+
| player_id | int |
| player_name | varchar |
+----------------+---------+
player_id is the primary key for this table.
Each row in this table contains the name and the ID of a tennis player.
Table: Championships
1
2
3
4
5
6
7
8
9
10
11
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| year | int |
| Wimbledon | int |
| Fr_open | int |
| US_open | int |
| Au_open | int |
+---------------+---------+
year is the primary key for this table.
Each row of this table containts the IDs of the players who won one each tennis tournament of the grand slam.
Write an SQL query to report the number of grand slam tournaments won by each player. Do not include the players who did not win any tournament.
Return the result table in any order.
The query result format is in the following example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Players table:
+-----------+-------------+
| player_id | player_name |
+-----------+-------------+
| 1 | Nadal |
| 2 | Federer |
| 3 | Novak |
+-----------+-------------+
Championships table:
+------+-----------+---------+---------+---------+
| year | Wimbledon | Fr_open | US_open | Au_open |
+------+-----------+---------+---------+---------+
| 2018 | 1 | 1 | 1 | 1 |
| 2019 | 1 | 1 | 2 | 2 |
| 2020 | 2 | 1 | 2 | 2 |
+------+-----------+---------+---------+---------+
Result table:
+-----------+-------------+-------------------+
| player_id | player_name | grand_slams_count |
+-----------+-------------+-------------------+
| 2 | Federer | 5 |
| 1 | Nadal | 7 |
+-----------+-------------+-------------------+
Player 1 (Nadal) won 7 titles: Wimbledon (2018, 2019), Fr_open (2018, 2019, 2020), US_open (2018), and Au_open (2018).
Player 2 (Federer) won 5 titles: Wimbledon (2020), US_open (2019, 2020), and Au_open (2019, 2020).
Player 3 (Novak) did not win anything, we did not include them in the result table.
MySQL Solution
1
2
3
4
5
6
7
8
select player_id, player_name,
sum((if(Wimbledon = player_id,1,0) +
if(Fr_open = player_id,1,0) +
if(US_open = player_id,1,0) +
if(Au_open = player_id,1,0))) as grand_slams_count
from Players inner join Championships
on Wimbledon = player_id or Fr_open = player_id or US_open = player_id or Au_open = player_id
group by player_id
LeetCode Database - Medium
LeetCode 1421
LeetCode 1440
LeetCode 1445
LeetCode 1454
LeetCode 1459
LeetCode 1468
LeetCode 1501
LeetCode 1532
LeetCode 1549
LeetCode 1555
LeetCode 1596
LeetCode 1613
LeetCode 1699
LeetCode 1709
LeetCode 1715
LeetCode 1747
LeetCode 1783
LeetCode 1811
More LeetCode Database
MySQL Tutorials