SQL行转列与列转行总结
多行转成一行的方法
多行转成一行,也就是所谓的行转列,比如一个uid的数据原来要多行来展示,现在把一个 uid 的数据浓缩到一行上,所以列就会增加,即行转列。
场景:现有用户表 student_score,包含 3 个字段 uid, subject, score,现在需要转换成一个用户一行数据: uid,math_score, chinese_score, english_score
原始数据
转换SQL
SELECT uid,
MAX(CASE WHEN subject = 'math' THEN score ELSE -1 END) AS math_score,
MAX(CASE WHEN subject = 'english' THEN score ELSE -1 END) AS english_score,
MAX(CASE WHEN subject = 'chinese' THEN score ELSE -1 END) AS chinese_score
FROM student_scores
GROUP BY uid
得到结果
一行转成多行的方法
场景:将用户的属性完全平铺开来,输出结果只有 3 个段: uid, field_key, field_value
原始数据
转换SQL
SELECT uid, field_key, field_value
FROM student_scores LATERAL VIEW EXPLODE(
STR_TO_MAP(CONCAT('math:', math_score,
',english:', english_score,
',chinese:', chinese_score))) tmp_table AS field_key, field_value;
-- 或者直接用map函数
SELECT uid, field_key, field_value
FROM student_scores LATERAL VIEW EXPLODE(
MAP('math', math_score,
'english', english_score,
'chinese', chinese_score)
) tmp_table AS field_key, field_value;
得到结果
LATERAL VIEW EXPLODE 的使用方法见站内文章:Hive Spark最常用函数指南