mysql数据库行转列

一、题目

有一张成绩表grade

有name,course,score三个字段

具体数据如下

二、题目要求

现在要求查询返回以下形式的数据

三、实现

原表数据是每科成绩都是以行展示

题目要求的数据是每科成绩以列展示

可以用三个case when来实现

case when course = '语文' then score end as Chinese_grade

case when course = '数学' then score end as math_grade

case when course = '英语' then score end as english_grade

效果如下

但是每个人的成绩还是有三条,需要用分组函数,再对成绩取最大值

select

name,

max(case when course = '语文' then score end) as Chinese_grade,

max(case when course = '数学' then score end) as math_grade,

max(case when course = '英语' then score end) as english_grade

from grade

group by name;

如果case when语句case when course = '语文' then score end as Chinese_grade 加一个else:

case when course = '语文' then score else 0 end as Chinese_grade

那也可以用sum进行求和

四、由二的数据变为一里面的数据(列转行)

select

name,

course,

score

from

(

select name, '语文' as course,Chinese_grade as score from grade

Union all

select name, '数学' as course,math_grade as score from grade

Union all

select name, '英语' as course,english_grade as score from grade

)

order by name

相关推荐
Small-Young1 小时前
数据库乐观锁深度解析:MySQL、PostgreSQL 实战 + Spring Boot 集成指南
数据库·spring boot·mysql·postgresql·乐观锁·并发控制
浮生若城1 小时前
MySQL 数据库基础
数据库·mysql
香蕉大香蕉(06敬畏市场)1 小时前
MySQL 单点详解(09)
java·数据库·mysql·面试·八股·大厂实习
lqbzlll3 小时前
MySQL 慢查询日志开了但看不懂?从 slow_query_log 到 EXPLAIN ANALYZE 一步步定位
数据库·mysql·adb
风翼靓崽4 小时前
centos7以mysql为例自建yum源
数据库·mysql·adb
秋名RG5 小时前
一条 SQL 语句在 MySQL 中的执行过程详解
数据库·sql·mysql
月夏5 小时前
一个汉字存成了 6 个字节:我用 HEX 揪出 MySQL 双重编码
mysql·docker·全栈
香蕉大香蕉(06敬畏市场)16 小时前
MySQL 单点详解(07)
java·数据库·mysql·ai·博客·八股