【问题标题】:How to get the index of element in an array and return the next element in Hive?如何获取数组中元素的索引并返回 Hive 中的下一个元素?
【发布时间】:2020-06-02 05:11:50
【问题描述】:

我有两张桌子。

表1:

id    |   array1
1     |     ['a', 'b', 'c']
2     |     ['b', 'a', 'c']
3     |     ['c', 'b', 'a']

表2:

id    |    value2
1     |     'b'
3     |     'a'

我希望得到下表:

id    |    value3
1     |     'c'
2     |     'b'
3     |     'c'

解释:我想要的是如果table1中的id在table2中不存在,则返回array1的第一个元素。如果table1中的id存在于table2中,则返回array1中value2的下一个元素(此时如果value2是array1中的最后一个元素,则返回array1的第一个元素)

我怎样才能实现这个目标?

【问题讨论】:

    标签: sql arrays hive hiveql


    【解决方案1】:

    使用poseexplode分解数组,与table2连接,计算连接行的位置,聚合,提取数组元素。

    演示:

    with table1 as(
    select stack(3,
    1, array('a', 'b', 'c'),
    2, array('b', 'a', 'c'),
    3, array('c', 'b', 'a')
    ) as (id,array1)
    ),
    
    table2 as(
    select stack(2,
    1,'b',
    3,'a'
    ) as (id,value2)
    )
    
    select s.id, nvl(s.array1[pos], s.array1[0]) value3
    from
    (
    select s.id, s.array1, min(case when t2.id is not null then s.pos+1 end) pos
    from
    (
    select t.id, t.array1, a.pos, a.value1
      from table1 t
           lateral view posexplode(t.array1) a as pos, value1
    )s left join table2 t2 on s.id=t2.id and s.value1=t2.value2  
    group by s.id, s.array1
    )s
    order by id
    

    结果:

    id  value3
    1   c
    2   b
    3   c 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多