我有一张这样的桌子
+-----+------------------------------+
| id | mapCol |
+-----+------------------------------+
| id1 | {key1:val1, key2:val2} |
| id2 | {key1:val3, key2:val4} |
+-----+------------------------------+
所以我可以轻松地执行查询
select explode(mapCol) as (key, val) from myTab where id='id1'
我明白了
+--------+-----+
| key | val |
+--------+-----+
| key1 | val1|
| key2 | val2|
+--------+-----+
我想生成一个这样的表
+-----+------+-----+
|id | key | val |
+-----+------+-----+
| id1 | key1 | val1|
| id1 | key2 | val2|
| id2 | key1 | val3|
| id2 | key2 | val4|
+-----+------------+
请注意,我想显示id
以及爆炸的行。此外,对于多个id,key
可能会重复,因此我希望行反映出来。基本上,id
+ key
应该是独一无二的。
我该怎么写这个查询?我试过了
select explode(mapCol) as (key, val), id from myTab
但我得到了
FAILED: SemanticException 1:66 Only a single expression in the SELECT clause is supported with UDTF's
使用lateral view:
with MyTable as -------use your table instead of this subquery
(select id, str_to_map(mapStr) mapCol
from
(
select stack(2,
'id1','key1:val1,key2:val2',
'id2','key1:val3,key2:val4'
) as (id, mapStr))s
) -------use your table instead of this subquery
select t.id, s.key, s.val
from MyTable t
lateral view outer explode(mapCol) s as key, val;
结果:
OK
id1 key1 val1
id1 key2 val2
id2 key1 val3
id2 key2 val4
Time taken: 0.072 seconds, Fetched: 4 row(s)
使用您的表而不是MyTable
子查询。
另请阅读关于侧面视图的答案:https://stackoverflow.com/a/51846380/2700344。