简体   繁体   English

在 bigquery 中添加/访问结构数组的索引

[英]Add/access the index of the array of structs in bigquery

I have a dataset like this我有这样的数据集

SELECT 'Blue' AS class, [STRUCT('Alice' AS name,18 AS age), STRUCT('Bob' AS name,17 AS age), STRUCT('Charlie' AS name,20 AS age)] as details

I would like to be able to add or access the index of each element of the array like below我希望能够添加或访问数组中每个元素的索引,如下所示

SELECT 'Blue' AS class, [STRUCT('Alice' AS name,18 AS age, 1 AS index), STRUCT('Bob' AS name,17 AS age, 2 AS index), STRUCT('Charlie' AS name,20 AS age, 3 AS index)] as details

The ultimate aim is to achieve something like this.最终目标是实现这样的目标。 So if the index can be accessed on the fly while creating the string_agg, that would be great因此,如果可以在创建 string_agg 时即时访问索引,那就太好了

with sub as (SELECT 'Blue' AS class, [STRUCT('Alice' AS name,18 AS age, 1 AS index), STRUCT('Bob' AS name,17 AS age, 2 AS index), STRUCT('Charlie' AS name,20 AS age, 3 AS index)] as details
)

select 
class,
STRING_AGG('person_'|| index || '_name =' || name || ', person_'|| index || '_age =' || age) AS output
from sub, unnest(details)
group by class

Thanks谢谢

Would you consider below without a temporary structure for a final result?您会考虑以下没有临时结构的最终结果吗?

WITH sample_data AS (
  SELECT 'Blue' AS class, [STRUCT('Alice' AS name,18 AS age), STRUCT('Bob' AS name,17 AS age), STRUCT('Charlie' AS name,20 AS age)] as details
)
SELECT class, STRING_AGG(FORMAT('person_%d_name=%s, person_%d_age=%d', idx + 1, name, idx + 1, age)) AS output
  FROM sample_data, UNNEST(details) WITH OFFSET idx
 GROUP BY 1;

在此处输入图像描述

  • WITH OFFSET clause provides you an index of each element in your array. WITH OFFSET子句为您提供数组中每个元素的索引。

For temporary structure, you can consider below.对于临时结构,您可以考虑以下内容。

SELECT class, ARRAY(SELECT AS STRUCT d.*, offset + 1 AS index FROM t.details d WITH OFFSET) details
  FROM sample_data t;
Adding indexes during creation.在创建过程中添加索引。
WITH sample_table AS (
  select 'Alice' AS ID, 1 as col1, 3 as col2, -2 as col3, 9 as col4
   union all
  select 'Bob' AS ID, -9 as col1, 2 as col2, 5 as col3, -6 as col4
)
SELECT ID, ARRAY_AGG(STRUCT(column, value, index) ORDER BY ABS(value) DESC LIMIT 3) output
  FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ABS(value) DESC) index 
      FROM sample_table UNPIVOT (value FOR column IN (col1, col2, col3, col4))
  ) 
 GROUP BY ID;

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM