【问题标题】:How to transpose concatenated values in columns to rows如何将列中的连接值转置为行
【发布时间】:2018-12-08 05:38:02
【问题描述】:

输入:

item   number
ABC     123

我想这样输出:

item   number
 A       1
 B       2
 C       3

【问题讨论】:

  • 问题不清楚。什么是 ABC 123?这是一列还是两列的一部分?到目前为止你尝试过什么?
  • 您是否尝试在纯 SQL 中执行此转换?蜂巢QL?火花? PySpark?

标签: sql hive apache-spark-sql hiveql pyspark-sql


【解决方案1】:

使用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!=''; 

【讨论】:

    猜你喜欢
    • 2020-12-20
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2023-03-31
    相关资源
    最近更新 更多