工作中经常用到的mysql行转列和列转行总结
一、行转列
-
创建数据表和创建数据
CREATE TABLE `student` ( `name` varchar(64) DEFAULT NULL COMMENT '名字', `subject` varchar(64) DEFAULT NULL COMMENT '科目', `score` float DEFAULT NULL COMMENT '分数' ) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT INTO student (NAME,SUBJECT,score) VALUES ('张三', '语文', 80), ('张三', '数学', 90), ('张三', '英语', 70), ('张三', '生物', 85), ('李四', '语文', 80), ( '李四', '数学', 92), ( '李四', '英语', 76), ('李四', '生物', 88), ( '码农', '语文', 60), ('码农', '数学', 82), ( '码农', '英语', 96), ( '码农', '生物', 78);
-
查询数据表中的内容(即转换前的结果)
SELECT * FROM student
-
先来看一下转换后的结果
可以看出,这里行转列是将原来的subject字段的多行内容选出来,作为结果集中的不同列,并根据name进行分组显示对应的score。
-
使用case…when…then 进行行转列
SELECT NAME , SUM(CASE SUBJECT WHEN '数学' THEN score ELSE 0 END ) 数学, SUM(CASE SUBJECT WHEN '语文' THEN score ELSE 0 END ) 语文, SUM(CASE SUBJECT WHEN '英语' THEN score ELSE 0 END ) 英语, SUM(CASE SUBJECT WHEN '生物' THEN score ELSE 0 END ) 生物 FROM student GROUP BY NAME;
-
使用IF() 进行行转列
SELECT NAME, SUM(IF(`subject`='数学',score,0)) AS '数学', SUM(IF(`subject`='语文',score,0)) AS '语文', SUM(IF(`subject`='英语',score,0)) AS '英语', SUM(IF(`subject`='生物',score,0)) AS '生物' FROM student GROUP BY NAME
注意点:
(1)SUM() 是为了能够使用GROUP BY根据NAME进行分组,因为每一个NAME对应的subject="语文"的记录只有一条,所以SUM() 的值就等于对应那一条记录的score的值。
假如NAME=‘张三’ and subject=‘语文’ 的记录有两条,则此时SUM() 的值将会是这两条记录的和,同理,使用Max()的值将会是这两条记录里面值最大的一个。但是正常情况下,一个user对应一个subject只有一个分数,因此可以使用SUM()、MAX()、MIN()、AVG()等聚合函数都可以达到行转列的效果。
(2)IF(subject=‘语文’,score,0) 作为条件,即对所有subject='语文’的记录的score字段进行SUM()、MAX()、MIN()、AVG()操作,如果score没有值则默认为0。
- 利用SUM(IF()) 生成列 + WITH ROLLUP 生成汇总行,并利用 IFNULL将汇总行标题显示为Total
运行结果:SELECT IFNULL(NAME,'total') AS NAME, SUM(IF(`subject`='数学',score,0)) AS '数学', SUM(IF(`subject`='语文',score,0)) AS '语文', SUM(IF(`subject`='英语',score,0)) AS '英语', SUM(IF(`subject`='生物',score,0)) AS '生物', SUM(IF(`subject`='total',score,0)) AS total FROM( SELECT NAME,IFNULL(`subject`,'total') AS `subject`,SUM(score) AS score FROM student GROUP BY NAME,`subject` WITH ROLLUP HAVING NAME IS NOT NULL )AS A GROUP BY NAME WITH ROLLUP;
- 利用SUM(IF()) 生成列 + UNION 生成汇总行,并利用 IFNULL将汇总行标题显示为 Total
运行结果:SELECT NAME, SUM(IF(`subject`='数学',score,0)) AS '数学', SUM(IF(`subject`='语文',score,0)) AS '语文', SUM(IF(`subject`='英语',score,0)) AS '英语', SUM(IF(`subject`='生物',score,0)) AS '生物', SUM(score) AS TOTAL FROM student GROUP BY NAME UNION SELECT 'TOTAL', SUM(IF(`subject`='数学',score,0)) AS '数学', SUM(IF(`subject`='语文',score,0)) AS '语文', SUM(IF(`subject`='英语',score,0)) AS '英语', SUM(IF(`subject`='生物',score,0)) AS '生物', SUM(score) FROM student
- 利用SUM(IF()) 生成列,直接生成结果不再利用子查询
运行结果:SELECT IFNULL(NAME,'TOTAL') AS NAME, SUM(IF(`subject`='数学',score,0)) AS '数学', SUM(IF(`subject`='语文',score,0)) AS '语文', SUM(IF(`subject`='英语',score,0)) AS '英语', SUM(IF(`subject`='生物',score,0)) AS '生物', SUM(score) AS TOTAL FROM student GROUP BY NAME WITH ROLLUP;
- 动态,适用于列不确定情况
运行结果:SET @EE=''; SELECT @EE :=CONCAT(@EE,'sum(if(subject= \'',SUBJECT,'\',score,0)) as ',SUBJECT, ',') AS aa FROM (SELECT DISTINCT SUBJECT FROM student) A ; SET @QQ = CONCAT('select ifnull(name,\'TOTAL\')as name,',@EE,' sum(score) as TOTAL from student group by name WITH ROLLUP'); -- SELECT @QQ; PREPARE stmt FROM @QQ; EXECUTE stmt; DEALLOCATE PREPARE stmt;
- 合并字段显示:利用group_concat()
运行结果:SELECT NAME,GROUP_CONCAT(`subject`,":",score)AS 成绩 FROM student GROUP BY NAME
group_concat(),手册上说明:该函数返回带有来自一个组的连接的非NULL值的字符串结果。
比较抽象,难以理解。通俗点理解,其实是这样的:group_concat()会计算哪些行属于同一组,将属于同一组的列显示出来。要返回哪些列,由函数参数(就是字段名)决定。分组必须有个标准,就是根据group by指定的列进行分组。
结论:groupconcat()函数可以很好的建属于同一分组的多个行转化为一个列。
二、列转行
-
创建数据表和创建数据
CREATE TABLE tb_score( id INT(11) NOT NULL AUTO_INCREMENT, userid VARCHAR(20) NOT NULL COMMENT '用户id', cn_score DOUBLE COMMENT '语文成绩', math_score DOUBLE COMMENT '数学成绩', en_score DOUBLE COMMENT '英语成绩', po_score DOUBLE COMMENT '政治成绩', PRIMARY KEY(id) )ENGINE = INNODB DEFAULT CHARSET = utf8;
INSERT INTO tb_score (userid,cn_score,math_score,en_score,po_score) VALUES ('001',90,92,80,0), ('002',88,90,75.5,0), ('003',70,85,90,82);
-
查询数据表中的内容(即转换前的结果)
SELECT * FROM tb_score
-
转换后:
-
UNION ALL
SELECT userid,'语文' AS course,cn_score AS score FROM tb_score UNION ALL SELECT userid,'数学' AS course,math_score AS score FROM tb_score UNION ALL SELECT userid,'英语' AS course,en_score AS score FROM tb_score UNION ALL SELECT userid,'政治' AS course,po_score AS score FROM tb_score ORDER BY userid
-
UNION
SELECT userid, '政治' COURSE, PO_SCORE AS SCORE FROM tb_score UNION SELECT userid, '英语' COURSE, EN_SCORE AS SCORE FROM tb_score UNION SELECT userid, '数学' COURSE, MATH_SCORE AS SCORE FROM tb_score UNION SELECT userid, '语文' COURSE , CN_SCORE AS SCORE FROM tb_score ORDER BY userid,COURSE;
这里将每个userid对应的多个科目的成绩查出来,通过UNION ALL将结果集加起来,达到上图的效果。
附:UNION与UNION ALL的区别(摘):
1.对重复结果的处理:UNION会去掉重复记录,UNION ALL不会;
2.对排序的处理:UNION会排序,UNION ALL只是简单地将两个结果集合并;
3.效率方面的区别:因为UNION 会做去重和排序处理,因此效率比UNION ALL慢很多;