标题
找出每一个球员赢得大满贯角逐的次数。结果不包含没有赢得角逐的球员的ID 。
结果集 无次序要求 。
准备数据
- Create table If Not Exists Players (player_id int, player_name varchar(20));
- Create table If Not Exists Championships (year int, Wimbledon int, Fr_open int, US_open int, Au_open int);
- Truncate table Players;
- insert into Players (player_id, player_name) values ('1', 'Nadal');
- insert into Players (player_id, player_name) values ('2', 'Federer');
- insert into Players (player_id, player_name) values ('3', 'Novak');
- Truncate table Championships;
- insert into Championships (year, Wimbledon, Fr_open, US_open, Au_open) values ('2018', '1', '1', '1', '1');
- insert into Championships (year, Wimbledon, Fr_open, US_open, Au_open) values ('2019', '1', '1', '2', '2');
- insert into Championships (year, Wimbledon, Fr_open, US_open, Au_open) values ('2020', '2', '1', '2', '2');
复制代码
分析数据
类型是行转列 一样平常要使用union(all)
第一步:将几行转成一列,使用union all
- select Wimbledon from Championships
- union all
- select Fr_open from Championships
- union all
- select US_open from Championships
- union all
- select Au_open from Championships;
复制代码
第二步:将两张表进行关联
- select player_id,player_name,count(*) as grand_slams_count
- from players join
- (select Wimbledon from Championships
- union all
- select Fr_open from Championships
- union all
- select US_open from Championships
- union all
- select Au_open from Championships) t1
- on t1.Wimbledon = player_id
- group by player_id, player_name;
复制代码
总结
- 若是行转列,使用union all
- 若是列转行, 使用if函数将数据拉宽
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |