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;

总结

相关推荐
我叫啥都行5 分钟前
计算机基础复习12.22
java·jvm·redis·后端·mysql
Zmxcl-00721 分钟前
IIS解析漏洞
服务器·数据库·microsoft
明矾java1 小时前
Mysql-SQL执行流程解析
数据库·sql·mysql
qq_397562311 小时前
android studio更改应用图片,和应用名字。
android·ide·android studio
峥嵘life1 小时前
Android Studio版本升级那些事
android·ide·android studio
蓬莱道人1 小时前
BenchmarkSQL使用教程
数据库
新手上路狂踩坑1 小时前
Android Studio的笔记--BusyBox相关
android·linux·笔记·android studio·busybox
p@nd@1 小时前
Oracle筑基篇-调度算法-LRU的引入
数据库·oracle·操作系统·lru
来一杯龙舌兰2 小时前
【MongoDB】使用 MongoDB 存储日志、审批、MQ等数据的案例及优点
数据库·mongodb
技术路上的苦行僧2 小时前
分布式专题(8)之MongoDB存储原理&多文档事务详解
数据库·分布式·mongodb