题88:
根据下面两个表请写出查询语句,查询出每一个球员赢得大满贯比赛的次数,结果不包含没有赢得比赛的球员的ID 。
其中:
- Players表:player_id 是这个表的主键,这个表的每一行给出一个网球运动员的 ID 和 姓名;
- Championships表:year 是这个表的主键,该表的每一行都包含在每场大满贯网球比赛中赢得比赛的球员的 ID。
解题思路:
(1)先用union all行转列
(2)连接(1)和Players表
(3)根据player_id进行分组
(4)查询想要的字段
select player_id ,player_name ,count(grand_slams) grand_slams_count
from (
select Wimbledon grand_slams
from Championships
union all
select Fr_open grand_slams
from Championships
union all
select US_open grand_slams
from Championships
union all
select Au_open grand_slams
from Championships
) t
left join Players p on t.grand_slams = p.player_id
group by player_id ;