Mysql中行转列与列转行

2021/6/16 2:21:37

本文主要是介绍Mysql中行转列与列转行,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

行转列:

#行转列
create table exam(
	id char(36) primary key comment '主键',
	name varchar(10) comment '姓名',
	course varchar(10) comment '课程',
	score int comment '分数'
);

insert into exam values (uuid(),'张三','语文',74);
insert into exam values (uuid(),'张三','数学',83);
insert into exam values (uuid(),'张三','英语',93);
insert into exam values (uuid(),'李四','语文',74);
insert into exam values (uuid(),'李四','数学',84);
insert into exam values (uuid(),'李四','英语',94);

#查看表中数据
select * from exam;

select name as Name,
	sum(if(`course`='语文',score,0)) as Chinese,
	sum(if(`course`='数学',score,0)) as Math,
	sum(if(`course`='英语',score,0)) as English,
	sum(score) as Total
from exam
group by name;
==========================================================================================
注释:sum函数也可以替换成max函数;如果name=’张三’ and course=’语文’ 的记录有两条,则sum()的值将会是两条记录的和,同理,若使用max()函数,则其值将会是两条记录中的最大值;

列转行:

#列转行
create table exam(
    id char(36) primary key comment '主键',
    name varchar(12) not null comment '姓名 ',
    chinese int(3) default 0 comment '语文',
    math int(3) default 0 comment '数学',
    english int(3) default 0 comment '英语'
)

insert into exam values (uuid(),'张三',90,92,80);
insert into exam values (uuid(),'李四',88,90,75);
insert into exam values (uuid(),'王五',70,85,90);

select * from exam;

第一步:
select '语文' as course
第二步:
select name,'语文' as course,chinese as score from exam
union all
select name,'数学' as course,math as score from exam
union all
select name,'英语' as course,english as score from exam
order by name
========================================================================================
注释:
①:将每个name对应的某一个科目的成绩查出来,然后通过union all将结果集加起来,最后按照name排序,最终实现列转行。
②:union与union all的区别:
	a、对重复结果的处理:union会去掉重复记录,union all不会;
	b、对排序的处理:union会排序,union all只是简单地将两个结果集合并;
	c、效率方面的区别:因为UNION 会做去重和排序处理,因此效率比union all慢很多;

 



这篇关于Mysql中行转列与列转行的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程