【问题标题】:Create multiple columns from existing Hive table columns从现有 Hive 表列创建多个列
【发布时间】:2021-05-14 01:10:52
【问题描述】:

如何从现有的 hive 表创建多个列。示例数据如下所示。

我的要求是仅在满足条件时才从现有表中创建 2 个新列。 col1 当代码 = 1 时。 col2 当 code=2 时。

预期输出:

请帮助如何在 Hive 查询中实现它?

【问题讨论】:

  • 最终表在 col1 和 col2 之间没有任何关系。我的意思是你可以使用这个 sql,但这也会产生空值。 select case when code=1 then col end as col1, case when code=2 then col end as col2 from table
  • 嗨@Koushik Roy,在我的情况下,列之间没有关系。这些 NULL 值如何出现在结果集中。请问有没有更好的办法?

标签: hive bigdata hiveql


【解决方案1】:

如果您将所需的值聚合到数组中,那么您可以只分解和过滤具有匹配位置的值。

演示:

with 

my_table as (--use your table instead of this CTE
select stack(8,
'a',1,
'b',2,
'c',3,
'b1',2,
'd',4,
'c1',3,
'a1',1,
'd1',4
) as (col, code)
)

select c1.val as col1, c2.val as col2 from
(
select collect_set(case when code=1 then col else null end) as col1,
       collect_set(case when code=2 then col else null end) as col2 
  from my_table where code in (1,2)
)s lateral view outer posexplode(col1) c1 as pos, val  
   lateral view outer posexplode(col2) c2 as pos, val
where c1.pos=c2.pos

结果:

col1    col2
a       b
a1      b1

如果数组大小不同,这种方法将不起作用。

另一种方法 - 计算 row_number 并在 row_number 上完全连接,如果 col1 和 col2 具有不同数量的值(某些值将为空),这将起作用:

with 

my_table as (--use your table instead of this CTE
select stack(8,
'a',1,
'b',2,
'c',3,
'b1',2,
'd',4,
'c1',3,
'a1',1,
'd1',4
) as (col, code)
),

ordered as
(
select code, col, row_number() over(partition by code order by col) rn
  from my_table where code in (1,2)
)

select c1.col as col1, c2.col as col2
  from (select * from ordered where code=1) c1 
       full join 
       (select * from ordered where code=2) c2 on c1.rn = c2.rn

结果:

col1    col2
a       b
a1      b1

【讨论】:

  • 嗨@leftjoin,感谢您的解决方案。是否可以提供独立查询(方法 2),因为您已将查询与 my_table 一起提出。
  • @Rajasekhar888 而不是 my_table 使用您的真实表。只需从 WITH 中删除 my_table 并将 MY_TABLE 替换为您的表名
猜你喜欢
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 2016-09-25
  • 1970-01-01
  • 1970-01-01
  • 2018-09-24
  • 2014-01-24
相关资源
最近更新 更多