如何在配置单元的复杂列中选择有限的值?

px9o7tmv  于 2021-06-24  发布在  Hive
关注(0)|答案(1)|浏览(283)

我有一张table,上面有身份证、姓名和熟练程度。“熟练程度”列是map数据类型的复杂列。如何将复杂Map数据类型中显示的数据量限制为2?
示例表

ID  | name   | Proficiency
003 | John   | {"Cooking":3, "Talking":6 , "Chopping":8, "Teaching":5}
005 | Lennon | {"Cooking":3, "Programming":6 }
007 | King   | {"Chopping":8, "Boxing":5 ,"shooting": 4}

select语句之后要显示的内容

ID  | name   | Proficiency
003 | John   | {"Cooking":3, "Talking":6 }
005 | Lennon | {"Cooking":3, "Programming":6 }
007 | King   | {"Chopping":8, "Boxing":5 }
hlswsv35

hlswsv351#

对于所需的固定数量的Map元素,可以使用 map_keys() 以及 map_values() 返回键和值数组的函数,可以使用数组索引访问键和值,然后使用 map() 功能:

with MyTable as -------use your table instead of this subquery
(select stack(3,
'003', 'John'  , map("Cooking",3,  "Talking",6 , "Chopping",8, "Teaching",5),
'005', 'Lennon', map("Cooking",3,  "Programming",6 ),
'007', 'King'  , map("Chopping",8, "Boxing",5 ,"shooting", 4)
) as (ID, name, Proficiency)
) -------use your table instead of this 

select t.ID, t.name, 
       map(map_keys(t.Proficiency)[0], map_values(t.Proficiency)[0],
           map_keys(t.Proficiency)[1], map_values(t.Proficiency)[1]
          ) as Proficiency
  from MyTable t

结果:

t.id    t.name  proficiency
003 John    {"Cooking":3,"Talking":6}
005 Lennon  {"Cooking":3,"Programming":6}
007 King    {"Boxing":5,"shooting":4}

map不保证按定义排序,map\键、map\值按定义返回无序数组,但它们在同一子查询中使用时顺序相同,因此键与其对应的值匹配。

相关问题