mysql - 行列数据转换技巧

MySQL 最核心的两种数据转换技巧

行转列:用 case when

列转行:用 union all

一、行转列(多行 → 多列)

用:CASE WHEN

原始数据(行)

plaintext 复制代码
name | subject | score
小明   语文      90
小明   数学      80
小明   英语      85

行转列后(列变多)

plaintext 复制代码
name | 语文 | 数学 | 英语
小明   90    80    85

代码:CASE WHEN

sql 复制代码
select
    name,
    max(case when subject='语文' then score end) as 语文,
    max(case when subject='数学' then score end) as 数学,
    max(case when subject='英语' then score end) as 英语
from score
group by name;

二、列转行(多列 → 多行)

用:UNION ALL

原始数据(列)

plaintext 复制代码
name | 语文 | 数学 | 英语
小明   90    80    85

列转行后(行变多)

plaintext 复制代码
name | subject | score
小明   语文      90
小明   数学      80
小明   英语      85

代码:UNION ALL

sql 复制代码
select name, '语文' as subject, 语文 as score from score
union all
select name, '数学' as subject, 数学 as score from score
union all
select name, '英语' as subject, 英语 as score from score;

最终终极口诀

行变多 → 上下拼 → UNION ALL

列变多 → 左右展 → CASE WHEN

相关推荐
研究员子楚13 小时前
GEO行业发展标准体系白皮书V2.0-第10卷 · 全球篇:跨国标准协同与全球品牌语义治理框架
数据库·人工智能·microsoft·架构·geo
Omics Pro14 小时前
深度学习多组学互作:组内+组间
数据库·人工智能·深度学习·mysql·搜索引擎·自然语言处理
残*影15 小时前
如何优雅地保存MySQL数据变更历史?
数据库·mysql
乐观的Terry15 小时前
3、数据库设计与领域实体
java·数据库·spring boot·spring cloud·ai编程
舞影天上15 小时前
RuoYi-Vue-Plus Docker 部署踩坑:MySQL 中文双重编码的根因与修复
数据库
Database_Cool_16 小时前
数据仓库弹性扩缩容怎么实现?AnalyticDB MySQL 在线扩容 0 中断实战
数据库·数据仓库·mysql·阿里云
Wzx19801216 小时前
Redis&ES——Retriever的抽象实现
数据库·人工智能·redis·elasticsearch
G.O.G.O.G16 小时前
《LeetCode SQL 从入门到进阶(MySQL)》06(下)
数据库·sql·oracle
zandy101118 小时前
多租户SaaS架构下的BI数据隔离与权限治理体系
数据库·架构·数据加密
多巴胺梦想家18 小时前
NoSQL 数据库:不只是关系型
数据库·nosql