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

相关推荐
hyx04121913 小时前
mysql第5次作业---hyx
数据库·mysql
nsjqj13 小时前
MySQL数据库:表的增删改查 [CRUD](进阶)【一】
数据库·mysql
运维 小白14 小时前
k8s 部署MySQL主从集群(一主两从)1.0
mysql·容器·kubernetes
就叫飞六吧14 小时前
MySQL不停机迁移完全指南
数据库·mysql
q***420515 小时前
在Spring Boot项目中使用MySQL数据库
数据库·spring boot·mysql
Wang's Blog16 小时前
MySQL: 操作系统对MySQL性能的影响及选型指南
数据库·mysql
挨踢攻城16 小时前
【OCP考试喜报】2025.11月 ORACLE OCP 考试通过
数据库·mysql·oracle·dba·oracle ocp·公众号:厦门微思网络·ocp19c
计算机学姐17 小时前
基于SpringBoot的健身房管理系统【智能推荐算法+可视化统计】
java·vue.js·spring boot·后端·mysql·spring·推荐算法
我科绝伦(Huanhuan Zhou)17 小时前
【免费】MySQL自动化巡检工具,一键生成WORD巡检报告
运维·mysql·自动化