sql—如何将列中的串联值转换为行

hpcdzsge  于 2021-06-27  发布在  Hive
关注(0)|答案(1)|浏览(395)

输入:

item   number
ABC     123

我想这样输出:

item   number
 A       1
 B       2
 C       3
sqxo8psd

sqxo8psd1#

使用拆分字符串 split() ,使用 posexplode() 使用侧视图。按空字符串拆分 '' 将生成包含额外空元素的数组,过滤掉它们,按它们在数组中的位置连接项和数字。
演示(用表替换s子查询):

select i.itm as item, n.nbr as number
from
(--replace this subquery with your table
 --this is two rows example
select stack(2,'ABC', '123',
               'DEF', '456') as (item, number)   
) s --your_table  
lateral view posexplode(split(s.item,'')) i as pos, itm 
lateral view posexplode(split(s.number,'')) n as pos, nbr 
where i.itm!='' and n.nbr!='' and i.pos=n.pos ;

结果:

OK
item    number
A       1
B       2
C       3
D       4
E       5
F       6
Time taken: 0.094 seconds, Fetched: 6 row(s)
hive>

更新:简化版本

select i.itm as item, substr(s.number,i.pos+1,1) as number
from
(--replace this subquery with your table
 --this is two rows example
select stack(2,'ABC', '123',
               'DEF', '456') as (item, number)   
) s --your_table  
lateral view posexplode(split(s.item,'')) i as pos, itm 
where i.itm!='';

相关问题