mysql 行转列 列转行
行转列
-->
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>
列转行
-->
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);
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 你所不知道的 C/C++ 宏知识
· 聊一聊 操作系统蓝屏 c0000102 的故障分析
· SQL Server 内存占用高分析
· .NET Core GC计划阶段(plan_phase)底层原理浅谈
· .NET开发智能桌面机器人:用.NET IoT库编写驱动控制两个屏幕
· 我干了两个月的大项目,开源了!
· 推荐一款非常好用的在线 SSH 管理工具
· 千万级的大表,如何做性能调优?
· 聊一聊 操作系统蓝屏 c0000102 的故障分析
· .NET周刊【1月第1期 2025-01-05】