Hive:posexplode v.s. explode 实现列转行

hive中explode相关的列转行总结

explode

explode 的输入只能是 array 或者map格式,按行输出array或map中的元素,比如:

sql 复制代码
select explode(split('1,2,3',','))

输出

explode(split('1,2,3', ','))
1
2
3
sql 复制代码
-- map explode
select explode(map('A','1','B','2','C','3'))

输出:

key value
A 1
B 2
C 3

posexplode()

在explode的基础上,输出了pos,结合lateral view 细腻表适用于对于多列进行转成多行的情况。

如:

sql 复制代码
select posexplode(split('1,2,3',','))

输出:

pos col
0 1
1 2
2 3

laterval view 虚拟表

结合udtf产出虚拟表:

sql 复制代码
lateralView: LATERAL VIEW udtf(expression) tableAlias AS columnAlias (',' columnAlias)*
fromClause: FROM baseTable (lateralView)*

lateral view explode(array)示例

sql 复制代码
select id,tim,single_tim 
from test.a lateral view explode(split(tim,',')) t as single_tim
--输出:
id	tim	single_tim
a,b,c,d	2:00,3:00,4:00,5:00	2:00
a,b,c,d	2:00,3:00,4:00,5:00	3:00
a,b,c,d	2:00,3:00,4:00,5:00	4:00
a,b,c,d	2:00,3:00,4:00,5:00	5:00
f,b,c,d	1:10,2:20,3:30,4:40	1:10
f,b,c,d	1:10,2:20,3:30,4:40	2:20
f,b,c,d	1:10,2:20,3:30,4:40	3:30
f,b,c,d	1:10,2:20,3:30,4:40	4:40
Time taken: 51.289 seconds, Fetched: 8 row(s)

lateral view posexplode(array)示例

sql 复制代码
select id,tim,single_id,single_tim from test.a 
lateral view posexplode(split(id,',')) t as single_id_index, single_id
lateral view posexplode(split(tim,',')) t as single_yim_index, single_tim
where single_id_index = single_yim_index;
-- 输出:
id	tim	single_id	single_tim
a,b,c,d	2:00,3:00,4:00,5:00	a	2:00
a,b,c,d	2:00,3:00,4:00,5:00	b	3:00
a,b,c,d	2:00,3:00,4:00,5:00	c	4:00
a,b,c,d	2:00,3:00,4:00,5:00	d	5:00
f,b,c,d	1:10,2:20,3:30,4:40	f	1:10
f,b,c,d	1:10,2:20,3:30,4:40	b	2:20
f,b,c,d	1:10,2:20,3:30,4:40	c	3:30
f,b,c,d	1:10,2:20,3:30,4:40	d	4:40

注意事项

  1. lateral view outer explode(),如果要拆分的字段有null值,需要使用lateral view outer 替代,避免数据缺失,参考文档见:https://blog.csdn.net/weixin_45857425/article/details/117933039;(https://blog.csdn.net/weixin_45857425/article/details/117933039)
  2. lateral view的位置是from后where条件前;
  3. 生成的虚拟表的表名不可省略;
  4. from后可带多个lateral view;

参考文档:

重点阅读:Hive--sql中的explode()函数和posexplode()函数
explode和lateral view explode使用记录

相关推荐
王小王-1233 天前
基于 Hive 的网易云音乐数据分析及可视化系统
hive·hadoop·数据分析·音乐数据分析·网易云音乐分析·hive音乐分析·hadoop网易云
TPBoreas5 天前
springboot3.5比2.x做了哪儿些提升
数据仓库·hive·hadoop
Nefu_lyh6 天前
【Hive】七、Hive 函数:聚合 / 统计 / 分位数 / 集合 / 高级分组
数据仓库·hive·hadoop
KANGBboy6 天前
hive UDF函数
数据仓库·hive·hadoop
王小王-1238 天前
基于商品评价的评论情感分析与可视化系统
hive·情感分析·商品评价分析·主题分析·商品评论分析
Nefu_lyh8 天前
【Hive】 八、Hive 计算引擎:MapReduce / Tez / Spark 对比与选型
hive·spark·mapreduce
白日与明月9 天前
Hive子查询中的ORDER BY陷阱:为什么排序“消失”了?
数据仓库·hive·hadoop
Nefu_lyh10 天前
【Hive】六、Hive 运算逻辑:数学 / 逻辑 / 条件 / 日期 / 字符串函数
数据仓库·hive·hadoop
AQin101211 天前
【对比向】既生瑜何生亮?不!Hive 和 Doris不一样
数据仓库·hive·hadoop·doris
AQin101211 天前
【对比向】细算“成本”——Hive vs. Doris
大数据·数据库·hive·doris·实时数仓