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;

总结

相关推荐
数据库那些事儿8 小时前
极智编程:基于Qoder+PolarDB Supabase 实现全栈VibeCoding
数据库
阿兰哥8 小时前
【调试篇5】TransactionTooLargeException 原理解析
android·性能优化·源码
该用户已不存在9 小时前
MySQL 与 PostgreSQL,该怎么选?
数据库·mysql·postgresql
GoldenaArcher9 小时前
GraphQL 工程化篇 III:引入 Prisma 与数据库接入
数据库·后端·graphql
川石课堂软件测试9 小时前
自动化测试之 Cucumber 工具
数据库·功能测试·网络协议·测试工具·mysql·单元测试·prometheus
爱吃水蜜桃的奥特曼9 小时前
玩Android Flutter版本,通过项目了解Flutter项目快速搭建开发
android·flutter
RestCloud10 小时前
StarRocks 数据分析加速:ETL 如何实现实时同步与高效查询
数据库
太过平凡的小蚂蚁10 小时前
Android 版本特性完全解析:从6.0到16.0的实用指南
android
lang2015092810 小时前
MySQL数据类型存储全解析
mysql
杨筱毅10 小时前
【底层机制】【Android】深入理解UI体系与绘制机制
android·底层机制