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