Mysql 行转列、列转行

本文介绍了如何使用SQL进行数据转换,包括将行数据转换为列数据(pivot操作)和将列数据转换为行数据(unpivot操作)。通过示例展示了创建表、插入数据、查询原始数据,以及具体的SQL语句实现,帮助理解这两种转换方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 行转列

建表语句

CREATE table student(
id int(8) primary key auto_increment,
name varchar(50) default null comment '姓名',
subject varchar(20)  default null comment '科目',
score double default 0 comment '分数'
);

测试数据


INSERT into student (name,subject,score) values ('张三','语文',99);
INSERT into student (name,subject,score) values ('张三','数学',100);
INSERT into student (name,subject,score) values ('张三','英语',87);
INSERT into student (name,subject,score) values ('李四','语文',89);
INSERT into student (name,subject,score) values ('李四','数学',97);
INSERT into student (name,subject,score) values ('李四','英语',88);

原始数据查询

SELECT * from student ;

行转列SQL语句:

SELECT name , MAX(CASE subject when '语文' then score else 0 end) as '语文', MAX(CASE subject when '数学' then score else 0 end) as '数学', MAX(CASE subject when '英语' then score else 0 end) as '英语' FROM student group by name;

 2. 列转行

建表语句

CREATE table student2(
id int(8) primary key auto_increment,
name varchar(50) default null comment '姓名',
subject1 varchar(20)  default null comment '语文',
subject2 varchar(20)  default null comment '英语',
subject3 varchar(20)  default null comment '英语'
);

测试数据

insert into student2 (name,subject1,subject2,subject3) values('张三','99','100','87');
insert into student2 (name,subject1,subject2,subject3) values('李四','89','97','88');

原始数据查询

SELECT * from student2 ;

 

 列转行SQL语句:

两种方式:

SELECT name,'语文' as subject , subject1 as score from student2
UNION 
SELECT name,'数学' as subject , subject2 as score from student2
UNION 
SELECT name,'英语' as subject , subject3 as score from student2 
order by name ;

SELECT 
    name ,
    '语文' as subject,
    MAX(subject1) as score
from
    student2
group by
    name
UNION 
SELECT 
    name ,
    '数学' as subject,
    MAX(subject2) as score
from
    student2
group by
    name
UNION 
SELECT 
    name ,
    '英语' as subject,
    MAX(subject3) as score
from
    student2
group by
    name
ORDER BY
    name ;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值