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

相关推荐
FungLeo1 小时前
FengCMS ·PHP+MySQL 升级实录· 设置发布与模板缓存:数据库与配置文件如何避免旧表单覆盖
数据库·mysql·php·工程实践·fengcms
斯维赤3 小时前
SELECT * 为什么是覆盖索引的天敌?
java·后端·mysql
FungLeo3 小时前
FengCMS · PHP+MySQL 升级实录· 编译缓存并发:锁定产物执行、避免重复发布与三类缓存清理
mysql·缓存·php·并发·fengcms
stormsha3 小时前
库存 5,10 个并发各买 1 件:为什么最后不剩 -5 件
java·数据库·mysql
一条闲鱼_mytube4 小时前
MySQL 幻读原理与可重复读隔离级别
数据库·mysql
FungLeo4 小时前
FengCMS · PHP+MySQL 升级实录 · 编辑器迁移:KindEditor → wangEditor5 +服务端 HTML Purifier
mysql·编辑器·php·富文本编辑器·fengcms
FungLeo4 小时前
FengCMS· PHP+MySQL 升级实录 ·模板编译器原理:{$var} 怎么编译成 PHP、缓存怎么失效
mysql·缓存·php·模板引擎·fengcms
FungLeo1 天前
FengCMS · PHP+MySQL 升级实录 · 旧后台备份三宗罪:漏空表、改写内容、按分号切 SQL 直接执行
sql·mysql·php·安全加固·fengcms
SA-D1 天前
MySQL 性能分析与库存一致性:从 Buffer Pool、B+ 树到执行计划
数据库·mysql
djjjx.2 天前
Mysql数据库基础篇(八):详细讲解复合查询、多表查询、自连接、多行、多列子查询与合并查询
数据库·mysql