数据库之列转行、行转列
数据库之列转行、行转列
创建表
# 建表语句 CREATE TABLE `TEST_TB_GRADE` ( `ID` int(10) NOT NULL AUTO_INCREMENT, `USER_NAME` varchar(20) DEFAULT NULL, `COURSE` varchar(20) DEFAULT NULL, `SCORE` float DEFAULT '0', PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
添加数据
# 添加数据 insert into TEST_TB_GRADE(USER_NAME, COURSE, SCORE) values ("张三", "数学", 34), ("张三", "语文", 58), ("张三", "英语", 58), ("李四", "数学", 45), ("李四", "语文", 87), ("李四", "英语", 45), ("王五", "数学", 76), ("王五", "语文", 34), ("王五", "英语", 89);
列转行 SQL
# 列转行 SELECT user_name , MAX(CASE course WHEN '数学' THEN score ELSE 0 END ) 数学, MAX(CASE course WHEN '语文' THEN score ELSE 0 END ) 语文, MAX(CASE course WHEN '英语' THEN score ELSE 0 END ) 英语 FROM test_tb_grade GROUP BY USER_NAME;
列转行的变化
行转列
需要先将转换后的数据存入到结果表中result
# 创建表结果表 CREATE TABLE `result` ( `USER_NAME` varchar(20) DEFAULT NULL, `COURSE` varchar(20) DEFAULT NULL, `SCORE` float DEFAULT '0' ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; # 将查询到的数据转入到结果表中 insert into result SELECT user_name , MAX(CASE course WHEN '数学' THEN score ELSE 0 END ) 数学, MAX(CASE course WHEN '语文' THEN score ELSE 0 END ) 语文, MAX(CASE course WHEN '英语' THEN score ELSE 0 END ) 英语 FROM test_tb_grade GROUP BY USER_NAME;
之后再进行行转列
# 行转列 select USER_NAME,'语文' COURSE,MAX(语文) as score from result GROUP by USER_NAME union ALL select USER_NAME,'数学' COURSE,MAX(数学) as score from result GROUP by USER_NAME union ALL select USER_NAME,'英语' COURSE,MAX(英语) as score from result GROUP by USER_NAME
行转列的变化
做自己的太阳,成为别人的光!