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;

总结

相关推荐
丫头,冲鸭!!!12 分钟前
记账网站3-连数据库
数据库·个人开发
灯澜忆梦30 分钟前
【MySQL12】进阶篇 | SQL优化
数据库·sql·mysql·性能优化
IvorySQL37 分钟前
PostgreSQL 日报|PG18.5 回归测试崩溃问题(8 月 12 日)
大数据·数据库·人工智能·postgresql
ltl1 小时前
学习型查询优化器:Neo、Bao、Balsa 与 LLM-CBO
数据库
ltl1 小时前
持久内存退场之后:ZNS SSD 与下一代非易失内存
数据库
故乡dee云3 小时前
AWS 产品太多不会选?按“网站、数据库、文件、日志”4 类需求快速匹配
数据库·云计算·aws
怪奇云呼军4 小时前
从声音特征到 CRM 回流:闪电智能 Voice Agent 沟通策略自适应系统 v1 实战
android·人工智能·python·音视频·语音识别
曹牧5 小时前
C#:问号
前端·数据库·c#
奇树谦5 小时前
《现代 Key-Value 数据库原理:从 B+Tree 到 LSM Tree》-第五篇:现代数据库横向对比
数据库·lsm-tree
李白客5 小时前
分布式集群与数据库产业:从单机到集群的架构跃迁与市场重构
数据库·分布式·架构