leetcode 1783 Grand Slam Titles
题目分析:
题目是英文的,但是看下几张表就知道题目的意思是想干什么。
players表是运动员的id和运动员的name
Championships是运动员每一年的四场比赛的第一名的id。题目想要求表中运动员一共的获奖情况。
首先最重要的问题是列转行,我们可以直接使用union all进行,如下
select Wimbledon player_id from Championships union all
select Fr_open from Championships union all
select US_open from Championships union all
select Au_open from Championships
这个地方注意:一定要使用union all,不可以使用union,union是去重的,在表中player_id为1,2的有很多,一旦去重就不是我们想要的结果。union all是不去重的,这也是两者之间的区别
接着对上面结果直接进行求和
select player_id,count(player_id) from (
select Wimbledon player_id from Championships union all
select Fr_open from Championships union all
select US_open from Championships union all
select Au_open from Championships) F group by player_id
对求和的结果进行inner join ,就是最后的结果
select F1.player_id,P.player_name,nums grand_slams_count from (
select player_id,count(player_id) nums from (
select Wimbledon player_id from Championships union all
select Fr_open from Championships union all
select US_open from Championships union all
select Au_open from Championships) F group by player_id) F1 inner join Players P on F1.player_id = P.player_id
提交结果如下: