Mysql - 行轉列、列轉行

b9x_發表於2018-04-23


原文地址:https://blog.csdn.net/jx_870915876/article/details/52403472

行轉列

       有如圖所示的表,現在希望查詢的結果將行轉成列(合併欄位,表中以Name為標準)

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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
insert into TEST_TB_GRADE(USER_NAME, COURSE, SCORE)  values
("張三", "數學", 34),
("張三", "語文", 58),
("張三", "英語", 58),
("李四", "數學", 45),
("李四", "語文", 87),
("李四", "英語", 45),
("王五", "數學", 76),
("王五", "語文", 34),
("王五", "英語", 89);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

       查詢語句:

       此處用之所以用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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

       結果展示:

2

列轉行

       有如圖所示的表,現在希望查詢的結果將列成行(少轉多)

3

       建表語句如下:

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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
insert into TEST_TB_GRADE2(USER_NAME, CN_SCORE, MATH_SCORE, EN_SCORE) values
("張三", 34, 58, 58),
("李四", 45, 87, 45),
("王五", 76, 34, 89);
  • 1
  • 2
  • 3
  • 4

查詢語句:

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;
  • 1
  • 2
  • 3
  • 4

       結果展示:

4

相關文章