问题描述
针对以下问题编写 Hive 查询以打印 ID 值,如果 Id 为 1,则打印 Id 1 次,如果 Id 值为 2,则打印 Id 2 次以此类推
Input Table
Id
---
1
2
3
4
Output
-------
Id
--
1
2
2
3
3
3
4
4
4
4
解决方法
使用space(id-1)
获取长度= id-1的空格字符串,拆分字符串并使用lateral view + explode
生成行。
演示:
with your_table as (
select stack (4,1,2,3,4) as id
)
select t.id
from your_table t
lateral view outer explode(split(space(id-1),' ')) e
结果:
t.id
1
2
2
3
3
3
4
4
4
4
更多解释:
split(space(id-1),' ')
- 这会产生 id-1 空格的数组
explode()
- 是一个表生成函数,从数组生成表
lateral view outer
的工作方式类似于主表与由爆炸生成的表的左连接。对于每一行,它与explode() 的每一行连接,并以这种方式为每一行生成重复项。