MySQL行轉列、列轉行

1、行轉列       

有如圖所示的表,如今但願查詢的結果將行轉成列

 

建表語句以下:

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,防止出現NULLsql

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;

 結果展現:

 

 

2、列轉行       

有如圖所示的表,如今但願查詢的結果將列成行

建表語句以下:

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;

結果展現:

相關文章
相關標籤/搜索