首页 > 解决方案 > Google BigQuery:UNNEST 结构数组和未嵌套项作为结构

问题描述

我有一个关于UNNESTArray-column 的问题。

我的源表架构如下所示

fields:
 - id:                                  STRING::NULLABLE
 - response_choices:                    RECORD::REPEATED
 - response_choices.response_option_id: STRING::NULLABLE
 - response_choices.position:           INT64::NULLABLE
 - response_choices.rendered_position:  INT64::NULLABLE
 - response_choices.responded_at:       DATETIME::NULLABLE

当我执行以下查询时

SELECT
  * EXCEPT(response_choices),
  STRUCT(
    ro.response_option_id AS response_option_id,
    ro.position AS position,
    ro.rendered_position AS rendered_position,
    ro.response_datetime AS responded_at
  ) AS response_choice
FROM my_responses_table,
  UNNEST(response_choices) AS ro

查询返回的数据既包括结构(如上定义),但也将结构平面的列添加到结果中。所以架构如下所示

fields:
  - id:                                  STRING::NULLABLE
  - response_option_id:                  STRING::NULLABLE
  - position:                            INT64::NULLABLE
  - rendered_position:                   INT64::NULLABLE
  - responded_at:                        DATETIME::NULLABLE
  - response_choice:                     RECORD::NULLABLE
  - response_choice.response_option_id:  STRING::NULLABLE
  - response_choice.position:            INT64::NULLABLE
  - response_choice.rendered_position:   INT64::NULLABLE
  - response_choice.responded_at:        DATETIME::NULLABLE

但是,我会以一种只添加一个带有结构的字段的方式来取消数组。原因是 struct 中的某些字段与表源中已经存在的字段冲突。

我想得到类似下面的东西

fields:
  - id:                                  STRING::NULLABLE
  - response_choice:                     RECORD::NULLABLE
  - response_choice.response_option_id:  STRING::NULLABLE
  - response_choice.position:            INT64::NULLABLE
  - response_choice.rendered_position:   INT64::NULLABLE
  - response_choice.responded_at:        DATETIME::NULLABLE

任何正确方向的建议或指示将不胜感激!谢谢

标签: google-bigquery

解决方案


以下是 BigQuery 标准 SQL

#standardSQL
select t.* except(response_choices), 
  response_choice
from `project.dataset.my_responses_table` t,
unnest(response_choices) response_choice

推荐阅读