从蜂巢中的多行旋转到多列

时间:2019-09-08 02:27:57

标签: hive

我有一个如下的配置单元表

(id:int, vals: Map<String, int> , type: string)
id, vals, type
1, {"foo": 1}, "a"
1, {"foo": 2}, "b"
2, {"foo": 3}, "a"
2, {"foo": 1}, "b"

现在只有两种类型 我想将其更改为以下模式

id, type_a_vals, type_b_vals
1, {"foo", 1}, {"foo": 2}
2, {"foo": 3}, {"foo": 1}

如果缺少任何“类型”,它可以为空吗?

1 个答案:

答案 0 :(得分:1)

牢记map列的一种简单方法是使用self join

select ta.id,ta.vals,tb.vals
from (select * from tbl where type = 'a') ta 
full join (select * from tbl where type = 'b') tb on ta.id = tb.id 

您可以使用条件聚合来解决如下问题。但是,在map列上执行此操作会产生 错误

select id
      ,max(case when type = 'a' then vals end) as type_a_vals
      ,max(case when type = 'b' then vals end) as type_a_vals
from tbl
group by id