首页 > 解决方案 > 在 BigQuery 中更新结构数组中的值

问题描述

我正在寻找一种简单的方法来使用 SQL 更新结构数组中的值。假设我们有一张桌子:

CREATE TABLE schema.table
(
    date DATE,
    weights ARRAY<STRUCT<animal STRING, value FLOAT64>>
)
;

insert into schema.table
select cast('2020-01-01' as date), [('dog', 10.2), ('bird', 0.7), ('dragon', 3.2)]
union all
select cast('2020-01-02' as date), [('dog', 10.3), ('bird', 0.7)]
union all
select cast('2020-01-03' as date), [('dragon', 3.3)]

所以表格看起来像:

在此处输入图像描述

我想以某种方式更新此表并将所有dragon名称更改为cat.

标签: sqlarraysdata-structuresgoogle-bigquery

解决方案


以下是 BigQuery 标准 SQL

#standardSQL
UPDATE `project.dataset.table` t
SET weights =  
  ARRAY(
    SELECT AS STRUCT IF(animal = 'dragon', 'cat', animal) animal, value
    FROM t.weights 
  ) 
WHERE TRUE

推荐阅读