行转列
--> ![](https://i-blog.csdnimg.cn/blog_migrate/a727e34241a6bdca19869318a194ef59.png)
SELECT user_name , MAX(CASE course WHEN '数学' THEN score END ) 数学, MAX(CASE course WHEN '语文' THEN score END ) 语文, MAX(CASE course WHEN '英语' THEN score END ) 英语 FROM test_tb_grade GROUP BY USER_NAME;
在 mybatis 中实现 动态行转列
<select id="list" resultType="java.util.HashMap"> SELECT user_name , <if test="courses != null"> <foreach collection="courses " item="item" separator=","> MAX(CASE course WHEN #{item} THEN score END ) "${item}" </foreach> </if> FROM test_tb_grade GROUP BY USER_NAME; </select>
列转行
-->![](https://i-blog.csdnimg.cn/blog_migrate/da60b3daf66cd333867b450d3c758ffb.png)
select user_name, '语文' as COURSE , CN_SCORE as SCORE from test_tb_grade2 union select user_name, '数学' as COURSE, MATH_SCORE as SCORE from test_tb_grade2 union select user_name, '英语' as COURSE, EN_SCORE as SCORE from test_tb_grade2 order by user_name,COURSE;
表数据:
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); 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);