MySQL高阶1783-大满贯数量

题目

找出每一个球员赢得大满贯比赛的次数。结果不包含没有赢得比赛的球员的ID 。

结果集 无顺序要求

准备数据

python 复制代码
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');
复制代码
Championships表
复制代码
Players表

分析数据

类型是行转列 一般要使用union(all)

第一步:将几行转成一列,使用union all

sql 复制代码
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;

第二步:将两张表进行关联

sql 复制代码
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;

总结

相关推荐
瓜牛_gn1 小时前
mysql特性
数据库·mysql
奶糖趣多多2 小时前
Redis知识点
数据库·redis·缓存
CoderIsArt3 小时前
Redis的三种模式:主从模式,哨兵与集群模式
数据库·redis·缓存
师太,答应老衲吧5 小时前
SQL实战训练之,力扣:2020. 无流量的帐户数(递归)
数据库·sql·leetcode
Yaml46 小时前
Spring Boot 与 Vue 共筑二手书籍交易卓越平台
java·spring boot·后端·mysql·spring·vue·二手书籍
Channing Lewis6 小时前
salesforce case可以新建一个roll up 字段,统计出这个case下的email数量吗
数据库·salesforce
追风林6 小时前
mac 本地docker-mysql主从复制部署
mysql·macos·docker
毕业设计制作和分享7 小时前
ssm《数据库系统原理》课程平台的设计与实现+vue
前端·数据库·vue.js·oracle·mybatis
ketil277 小时前
Redis - String 字符串
数据库·redis·缓存
Hsu_kk8 小时前
MySQL 批量删除海量数据的几种方法
数据库·mysql