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

相关推荐
Fleshy数模7 小时前
CentOS7 安装配置 MySQL5.7 完整教程(本地虚拟机学习版)
linux·mysql·centos
az44yao8 小时前
mysql 创建事件 每天17点执行一个存储过程
mysql
秦老师Q9 小时前
php入门教程(超详细,一篇就够了!!!)
开发语言·mysql·php·db
橘子1310 小时前
MySQL用户管理(十三)
数据库·mysql
Dxy123931021610 小时前
MySQL如何加唯一索引
android·数据库·mysql
我真的是大笨蛋10 小时前
深度解析InnoDB如何保障Buffer与磁盘数据一致性
java·数据库·sql·mysql·性能优化
怣5010 小时前
MySQL数据检索入门:从零开始学SELECT查询
数据库·mysql
人道领域11 小时前
javaWeb从入门到进阶(SpringBoot事务管理及AOP)
java·数据库·mysql
千寻技术帮12 小时前
10404_基于Web的校园网络安全防御系统
网络·mysql·安全·web安全·springboot
spencer_tseng12 小时前
MySQL table backup
mysql