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

相关推荐
泯仲2 小时前
从零起步学习MySQL 第十章:深入了解B+树及B+树的性能优势
b树·学习·mysql
hjxu20162 小时前
【 MySQL 速记5】插入
android·数据库·mysql
sea12164 小时前
Flask配置MySQL连接信息的最佳实践
python·mysql·flask
dreamread5 小时前
Linux下MySQL的简单使用
linux·mysql·adb
夕除5 小时前
MySQL--008
数据库·mysql
顶点多余5 小时前
MysqL---表的内外连接 (重点)
数据库·mysql
6+h5 小时前
【MySQL】锁机制详解
数据库·mysql
xyyaihxl5 小时前
mysql中主键索引和联合索引的原理解析
数据库·mysql
lihao lihao5 小时前
MySQl复合查询
数据库·sql·mysql
aq55356005 小时前
MySQL-触发器(TRIGGER)
android·数据库·mysql