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

相关推荐
武子康4 小时前
Java-138 深入浅出 MySQL Spring Boot 事务传播机制全解析:从 REQUIRED 到 NESTED 的实战详解 传播机制原理
java·大数据·数据库·spring boot·sql·mysql·事务
東雪蓮☆5 小时前
MySQL 全量 + 增量备份脚本(RPM 安装)实践与问题解析
linux·运维·mysql
lang2015092816 小时前
揭秘InnoDB磁盘I/O与存储空间管理
数据库·mysql
swaveye906016 小时前
轻量服务器创建mysql,并配置远程连接
服务器·mysql·adb
理智的煎蛋20 小时前
基于 Celery 的分布式文件监控系统
redis·分布式·python·mysql·mongodb
Albert Edison1 天前
【MySQL】表的操作
数据库·mysql·oracle
欢喜躲在眉梢里1 天前
mysql中的日志
android·运维·数据库·mysql·adb·日志·mysql日志
合作小小程序员小小店1 天前
web开发,在线%校园,论坛,社交管理%系统,基于html,css,python,django,mysql
数据库·后端·mysql·django·web app
-L71 天前
【MySQL数据库管理问答题】第14章 使用 MySQL InnoDB 集群实现高可用性
数据库·mysql