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;

总结

相关推荐
shizhan_cloud4 分钟前
MySQL 索引优化 + 慢查询日志
数据库·mysql
Drache_long12 分钟前
MySQL数据库(故障排除)
数据库·mysql
2303_8212873813 分钟前
如何清洗SQL输入数据_使用框架内置的ORM处理数据交互
jvm·数据库·python
清风雅雨13 分钟前
AI编程:OA流程明细表中多个金额字段由整数改为2位小数
数据库·ai编程
菜鸟上路_lbz14 分钟前
sqlserver存储过程查询缓慢锁表分析
数据库·sqlserver
Elastic 中国社区官方博客16 分钟前
在 Elasticsearch 中使用利润率与流行度加权来优化电商搜索
大数据·数据库·elasticsearch·搜索引擎·全文检索
van久44 分钟前
Day32:项目性能优化(EF Core + 分页 + 全异步)
数据库·oracle·性能优化
shaoming37761 小时前
浏览器动作开发:地址栏图标点击事件、弹出页面设计
android·mysql·adb
Dxy12393102161 小时前
Python请求方式介绍:JSON、表单及其他常见数据传输格式
数据库·python·json
赏金术士1 小时前
Kotlin 协程与挂起函数(Coroutines & suspend)入门到实战
android·开发语言·kotlin