Mysql行转列

来源:互联网 发布:淘宝刷单被发现 编辑:程序博客网 时间:2024/06/06 04:12

准备表数据

CREATE TABLE test_user (  name varchar(50) DEFAULT NULL,  subject varchar(50) DEFAULT NULL,  score int(11) DEFAULT NULL);insert into test_user values('zhangsan' , 'chinese' , 10),('zhangsan' , 'math' , 20),('zhangsan' , 'english' , 30),('lily' , 'chinese' , 40),('lily' , 'math' , 50),('lily' , 'english' , 60),('mini' , 'chinese' , 70),('mini' , 'math' , 80),('mini' , 'english' , 90);select * from test_user

行转列

select name, max(IF(subject = 'chinese',score,0)) as 'chinese', max(IF(subject = 'math',score,0)) as 'math', max(IF(subject = 'english',score,0)) as 'english', sum(score) as'total'from test_usergroup by name

分析执行计划:
1、对表中数据根据name进行分组
2、对分组后的数据,进行处理。


0 0