行轉列
例如:把圖1轉換成圖2結果展示

圖1

圖2
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;
列轉行
例如:把圖1轉換成圖3結果展示

圖3
列轉行SQL:
select user_name, '語文' COURSE , CN_SCORE as SCORE from test_tb_grade2 union select user_name, '數學' COURSE, MATH_SCORE as SCORE from test_tb_grade2 union select user_name, '英語' COURSE, EN_SCORE as SCORE from test_tb_grade2 order by user_name,COURSE;
【轉載自:http://blog.csdn.net/jx_870915876/article/details/52403472】
