微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Bigquery:查找在数组中首次找到指定元素的索引

如何解决Bigquery:查找在数组中首次找到指定元素的索引

我正在使用Bigquery,我有一个包含数组的数据集,我想在其中提取首次找到指定元素的索引。我在Bigquery中找不到实现我想要的功能。 Dataprep具有arrayindexof函数,但在编写本文时在Bigquery中尚不可用。 https://cloud.google.com/dataprep/docs/html/ARRAYINDEXOF-Function_136155116

如果arrayindexof存在于Bigquery中,那么我们将使用它。

select arrayindexof(metric,'b') as index,value[offset(arrayindexof(metric,'b'))] as b
from (select ['a','b','c'] as metric,[1,2,3] as value
      union all select ['b','c'],[4,5]
      union all select ['c'],[6])

所需结果:

Row|index|   b
--------------
  1|    1|   2
  2|    0|   4
  3| NULL|NULL

有什么想法可以在Bigquery中达到预期的结果吗?

亲切的问候,

解决方法

以下是用于BigQuery标准SQL

#standardSQL
select 
  ( select offset 
    from unnest(metric) m with offset 
    where m = 'b'
  ) index,( select v
    from unnest(metric) m with offset
    join unnest(value) v with offset
    using(offset)
    where m = 'b'
  ) b
from `project.dataset.table` 

如果要应用于您的问题的样本数据-输出为

enter image description here

另一个选项(显然具有相同的结果):

#standardSQL
select index,value[offset(index)] value
from (
  select *,( select offset 
      from unnest(metric) m with offset 
      where m = 'b'
    ) index
  from `project.dataset.table` 
)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。