MySQL行转列与列转行

列转行

数据准备:

create table student(
stu_id int primary key,
stu_name varchar(20),
chinese_score int,
math_score int);

insert into student values(1,'Tom',90,80);
insert into student values(2,'Mike',70,90);
insert into student values(3,'Jane',80,60);

在这里插入图片描述

select stu_id,stu_name,'Chinese' as course,chinese_score as score from student
		UNION
select stu_id,stu_name,'Math' as course,math_score as score from student

在这里插入图片描述
说明:列转行实际上是将一列数据拆分。可将查询结果进行合并实现。

行转列

将多行数据进行合并。
数据准备:(CTAS方式直接创建表)

create table student1 as  SELECT * from (
select stu_id,stu_name,'Chinese' as course,chinese_score as score from student
		UNION
select stu_id,stu_name,'Math' as course,math_score as score from student) as temp;

在这里插入图片描述
方式一:MAX(CASE …WHEN…THEN)

SELECT stu_id,stu_name,
							MAX(CASE 
									WHEN course='Chinese' THEN
												score
									END
									)AS chinese,
							MAX(CASE 
									WHEN course='Math' THEN
												score
									END
									)AS math
from student1 group by stu_id;

在这里插入图片描述

方式二:GROUP_CONCAT

SELECT stu_id,stu_name,GROUP_CONCAT(course,':',score) as course_score
				from student1 group by stu_id;

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43695091/article/details/89053797