-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path34-01783-grand-slam-titles.sql
40 lines (34 loc) · 1.27 KB
/
34-01783-grand-slam-titles.sql
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
30
31
32
33
34
35
36
37
38
39
40
-- beginner level solution
-- all player ids in a single column, count those, join with Players for name
with CTE as
(select Wimbledon as id
from Championships
union all
select Fr_open as id
from Championships
union all
select US_open as id
from Championships
union all
select Au_open as id
from Championships)
select c.id as player_id, p.player_name, count(c.id) as grand_slams_count
from CTE c
join Players p
on c.id = p.player_id
group by 1
------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- using cross join
-- using aggregate function because we want to group by each player
-- using cross join, we are getting all players and all championships
-- so we use having to filter only those players who have won at least 1
select p.player_id, p.player_name,
sum(case when p.player_id = c.Wimbledon then 1 else 0 end +
case when p.player_id = c.Fr_open then 1 else 0 end +
case when p.player_id = c.US_open then 1 else 0 end +
case when p.player_id = c.Au_open then 1 else 0 end) as grand_slams_count
from Players p
cross join Championships c
group by p.player_id
having grand_slams_count > 0
-- amazon- 1