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;

总结

相关推荐
保定公民25 分钟前
达梦数据库使用cp备份集恢复报错分析与解决
数据库
wd_cloud1 小时前
QT/6.7.2/Creator编译Windows64 MySQL驱动
开发语言·qt·mysql
少废话h2 小时前
Redis主从与集群搭建全指南
大数据·linux·redis·mysql
モンキー・D・小菜鸡儿2 小时前
Android Jetpack Compose 基础控件介绍
android·kotlin·android jetpack·compose
中冕—霍格沃兹软件开发测试2 小时前
测试用例库建设与管理方案
数据库·人工智能·科技·开源·测试用例·bug
The star"'2 小时前
mysql(4-7)
数据库·mysql·adb
无风之翼2 小时前
android15 休眠唤醒过程中有时候屏幕显示时间一闪而过
android·锁屏
The star"'2 小时前
mysql(1-3)
运维·mysql·云计算
jiayong233 小时前
Redis面试深度解析
数据库·redis·面试
思成不止于此3 小时前
【MySQL 零基础入门】DQL 核心语法(四):执行顺序与综合实战 + DCL 预告篇
数据库·笔记·学习·mysql