mysql 行转列

来源:互联网 发布:github for windows 编辑:程序博客网 时间:2024/05/18 00:02

1.准备表和数据

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);
效果图


2.行转列

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




IF(subject = 'chinese',score,0),指定列的值,若,是指定列,则列的值为score或者0,所以,会有max函数的出现

max(),最大值,根据分组,会出现三条数据,当前score的分数、0、0,使用max函数,则匹配到需求数据


tips:

此种方法,需要提前知道列名,有一定局限性。如果需要套公式的效果,则可能需要存储过程,一条sql可能搞不定


0 0