SQL中的行转列,列转行
SQL中的行列转换
1. 导入
有这样两张表,这两张表如何互相转换
student_table
score_table
2. 行转列
使用 UNION ALL
-- 行转列
SELECT name,'语文' as subject,chinese_score as score
FROM student_table
UNION ALL
SELECT name,'数学' as subject,math_score as score
FROM student_table
UNION ALL
SELECT name,'英语' as subject,english_score as score
FROM student_table
注:union ,union all 的区别是union可以去重,确定不会重复的数据,使用 union all 的性能会高一些
3. 列转行
-- 列转行
SELECT name,
MAX(CASE WHEN subject = '语文' THEN score ELSE 0 END)as chinese_score,
MAX(CASE WHEN subject = '数学' THEN score ELSE 0 END)as math_score,
MAX(CASE WHEN subject = '英语' THEN score ELSE 0 END)as english_score
FROM score_table
GROUP BY name
总结
列转行: case when…then…else…end + Group By + MAX取值
行转列: 使用UNION拼接多个查询结果