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;

总结

相关推荐
爱吃火鸡面呀6 分钟前
MySQL DQL 子查询详解:从标量、列、行到表子查询的完整实战
大数据·数据库·mysql
harmony&23 分钟前
OpenStack 云平台管理实战:从 Keystone 认证到 Nova 计算调度
数据库·openstack
betazhou1 小时前
Apache Seatunnel 抽取Oracle数据库测试
数据库·oracle·apache·seatunnel
devilnumber3 小时前
Oracle 与 MySQL substr 函数差异总结
java·数据库·mysql·oracle
码农coding3 小时前
android12 开机动画分析
android
—Miss. Z—3 小时前
计算机等级考试三级数据库技术—选择题
数据库·mysql
www_aiyuanma_vip3 小时前
PC 手机电商(MySQL 版)
数据库·mysql·智能手机
Databend3 小时前
AI 时代的数据工程挑战:从复杂链路走向统一数据底座
大数据·数据库·云计算
treacle田3 小时前
达梦数据库-Linux DM数据守护主备集群缩改为单机-记录总结
linux·服务器·数据库·主备集群改单机