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

相关推荐
廋到被风吹走3 小时前
【数据库】【MySQL】InnoDB外键解析:约束机制、性能影响与最佳实践
android·数据库·mysql
Logic1013 小时前
《Mysql数据库应用》 第2版 郭文明 实验6 数据库系统维护核心操作与思路解析
数据库·sql·mysql·学习笔记·计算机网络技术·形考作业·国家开放大学
@nengdoudou4 小时前
KingbaseES支持 mysql 的find_in_set函数
数据库·mysql
梁萌5 小时前
保姆级的MySQL执行计划(Explain)解读
数据库·mysql·explain·执行计划
cq林志炫5 小时前
MySQL 英文逗号隔开的数据如何模糊精确查询
mysql
杨云龙UP6 小时前
MySQL 8.0.x InnoDB 写入链路优化:Redo Log 与 Buffer Pool 扩容与缓冲区调优实战记录-20251029
linux·运维·数据库·sql·mysql
UCoding9 小时前
新能源技术面试 -- 给出一套mysql备份容灾方案
mysql·面试·主从
CodeAmaz10 小时前
MySQL 事务隔离级别详解
数据库·mysql·事务隔离级别
千寻技术帮10 小时前
10398_基于SSM的教学评价管理系统
数据库·mysql·毕业设计·ssm·教学评价
PWRJOY11 小时前
【MySQL】使用mycli查看数据库的基本操作
数据库·mysql