首页 > 解决方案 > 在 Hive 中的多个列上展开

问题描述

我正在尝试在 Hive 的多个列中展开记录。

例如,如果我的数据集看起来像这样 -

COL_01  COL_02     COL_03
1       A, B       X, Y, Z
2       D, E, F    V, W

我想要这个作为输出 -

COL_01  COL_02  COL_03
1       A        X
1       B        Y
1       NULL     Z
2       D        V
2       E        W
2       F        NULL

有没有办法在 Hive 中做到这一点?

我看到了一些关于单列爆炸的帖子,但在这种情况下却没有看到多列。

标签: sqlarrayssplithivehiveql

解决方案


在子查询中分别展开并使用完全连接将它们连接起来。

with your_data as (
select stack(2,
1, 'A, B',     'X, Y, Z',
2, 'D, E, F',  'V, W'
) as (col_01, col_02, col_03)
) 

select nvl(s1.col_01,s2.col_01) as col_01, --do the same nvl() for all not exploded columns
       s1.col_02, s2.col_03
from
(select d.col_01, c2.pos2, c2.col_02 --explode col_02
  from your_data d
       lateral view outer posexplode(split(col_02,', ?')) c2 as pos2, col_02
)s1

full join

(select d.col_01, c3.pos3, c3.col_03 --explode col_03
  from your_data d
       lateral view outer posexplode(split(col_03,', ?')) c3 as pos3, col_03
)s2
on s1.col_01=s2.col_01 
   and s2.pos3=s1.pos2 --match position

结果:

col_01  s1.col_02   s2.col_03   
1          A           X    
1          B           Y    
1          NULL        Z    
2          D           V    
2          E           W    
2          F           NULL 

推荐阅读