mysql行轉列、列轉行
語句不難,不做多余解釋了,看語句時,從內往外一句一句剖析
行轉列
有如圖所示的表,現在希望查詢的結果將行轉成列
建表語句如下:
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);
查詢語句:
此處用之所以用MAX是為了將無數據的點設為0,防止出現NULL
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;
結果展示:
列轉行
有如圖所示的表,現在希望查詢的結果將列成行
建表語句如下:
CREATE TABLE `TEST_TB_GRADE2` ( `ID` int(10) NOT NULL AUTO_INCREMENT, `USER_NAME` varchar(20) DEFAULT NULL, `CN_SCORE` float DEFAULT NULL, `MATH_SCORE` float DEFAULT NULL, `EN_SCORE` float DEFAULT '0', PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
insert into TEST_TB_GRADE2(USER_NAME, CN_SCORE, MATH_SCORE, EN_SCORE) values ("張三", 34, 58, 58), ("李四", 45, 87, 45), ("王五", 76, 34, 89);
查詢語句:
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;
結果展示:
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!