mysql行转列和列转行

行转列

1、初始数据

在这里插入图片描述

2、行转列后的数据

在这里插入图片描述

3、sql语句

select name, 
max(CASE type WHEN '语文' THEN score.score else 0 END) '语文',
max(CASE type WHEN '数学' THEN score.score else 0 END) '数学',
max(CASE type WHEN '英语' THEN score.score else 0 END) '英语'
from score GROUP BY name;

这里使用max函数的原因是因为group by分组,没有max函数的话 他就会查询每个分组的第一个元组,所以max函数是不能少的。

列转行

1、初始数据

在这里插入图片描述

2、列转行后的数据

在这里插入图片描述

3、sql语句

select id,name, '语文' as course, chinese as score from score01
UNION ALL
select id,name, '数学' as course, math as score from score01
UNION ALL
select id,name, '英语' as course, english as score from score01
order by id

全部sql

==============================================行转列==============================================
CREATE TABLE `score` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `type` varchar(255) DEFAULT NULL,
  `score` int DEFAULT NULL,
  PRIMARY KEY (`id`)
);
INSERT into score VALUES(1,'张三','语文',70);
INSERT into score VALUES(2,'张三','数学',80);
INSERT into score VALUES(3,'张三','英语',90);
INSERT into score VALUES(4,'李四','语文',50);
INSERT into score VALUES(5,'李四','数学',60);
INSERT into score VALUES(6,'李四','英语',80);
INSERT into score VALUES(7,'王五','语文',60);
INSERT into score VALUES(8,'王五','数学',90);
INSERT into score VALUES(9,'王五','英语',80);

select * from score;

select name, 
max(CASE type WHEN '语文' THEN score.score else 0 END) '语文',
max(CASE type WHEN '数学' THEN score.score else 0 END) '数学',
max(CASE type WHEN '英语' THEN score.score else 0 END) '英语'
from score GROUP BY name;
 
==============================================列转行==============================================

CREATE TABLE `score01` (
  `id` int NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `chinese` int DEFAULT NULL,
  `math` int DEFAULT NULL,
  `english` int DEFAULT NULL,
  PRIMARY KEY (`id`)
);
INSERT INTO score01 VALUES(1,'张三',50,60,70);
INSERT INTO score01 VALUES(2,'李四',80,60,50);
INSERT INTO score01 VALUES(3,'王五',80,70,60);

select * from score01;

select id,name, '语文' as course, chinese as score from score01
UNION ALL
select id,name, '数学' as course, math as score from score01
UNION ALL
select id,name, '英语' as course, english as score from score01
order by id;
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shy好好学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值