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;

总结

相关推荐
wang24559819919 分钟前
【MySQL基础篇】概述及SQL指令:DDL及DML
sql·mysql·oracle
2401_898075121 小时前
Python在金融科技(FinTech)中的应用
jvm·数据库·python
IvorySQL1 小时前
PostgreSQL 技术日报 (3月14日)|AI 落地 PostgreSQL 拒绝 PPT 空谈
数据库·postgresql·开源
JavaGuide1 小时前
鹅厂面试:SELECT * 一定导致索引失效?常见索引失效场景有哪些?
java·数据库·后端·mysql·大厂面试
wmfglpz882 小时前
NumPy入门:高性能科学计算的基础
jvm·数据库·python
泯仲2 小时前
从零起步学习MySQL 第十二章:MySQL分页性能如何优化?
数据库·学习·mysql
IvorySQL2 小时前
直播预告|PostgreSQL 18.3 x IvorySQL 5.3:开启 AI 数据库新纪元
数据库·postgresql·开源
TDengine (老段)3 小时前
TDengine IDMP 组态面板 —— 创建组态
大数据·数据库·物联网·时序数据库·iot·tdengine·涛思数据
SelectDB3 小时前
Apache Doris + SelectDB:定义 AI 时代,实时分析的三大范式
大数据·数据库·数据分析