一、引言
1.1 声明
声明:
无
交流、合作请留言,24小时内回复!
1.2 简介
此文章主要记录了本人工作中所实际用到的SQL行转列/列转行的SQL语句,所涉及的数据库还较少,后续根据实际情况进行补充。
若有建议、指正、或其他需求可以留言讨论,共同学习、进步。
1.3 代办
需要不断丰富
二、列转行
2.1 hive数据库
有一张学生的考试成绩表(table_name:exam_score),其表结构为如下,每一个科目为一个字段:
# 下面sql语句执行环境为hivesql
create table exam_score(
name string comment '姓名',
chinese double comment '语文',
math double comment '数学',
english double comment '英语',
history double comment '历史'
)
insert into exam_score values('张三',89,98,87,92),('李四',92,97,88,95)
对表exam_score直接执行select * from exam_score
查询的结果形式如下表所示:
每一列展示一个科目的成绩
name | chinese | math | english | history |
---|---|---|---|---|
张三 | 89 | 98 | 87 | 92 |
李四 | 92 | 97 | 88 | 95 |
现在需要将查询结果显示成如下格式:
每一行展示一个科目的成绩
姓名 | 科目 | 成绩 |
---|---|---|
张三 | 语文 | 89 |
张三 | 数学 | 98 |
张三 | 英语 | 87 |
张三 | 历史 | 92 |
李四 | 语文 | 82 |
李四 | 数学 | 97 |
李四 | 英语 | 88 |
李四 | 历史 | 95 |
2.1.1 HiveSQL语法
select t1.name `姓名`,t2.course `科目`,t2.score `成绩`
from exam_score t1
lateral view explode(
map(
'语文',chinese,
'数学',math,
'英语',english,
'历史',history
)
) t2 as course,score
2.1.2 persto语法
select t1.name "姓名",t2.course "科目",t2.score "成绩"
from exam_score t1
cross join unnest(
array['语文','数学','英语','历史'],
array[chinese, math, english, history]
) t2 (course,score)