【问题标题】:Google BigQuery: UNNEST array of structs and unnested item as structGoogle BigQuery:UNNEST 结构数组和未嵌套项作为结构
【发布时间】:2020-10-19 17:22:26
【问题描述】:

我有一个关于UNNEST使用结构的数组列的问题。

我的源表架构如下所示

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

但是,我会以一种只添加一个包含结构的字段的方式对数组进行 UNNEST。原因是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

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

【问题讨论】:

  • 我认为您在问题顶部提供的架构(用于源表)有问题 - 请仔细检查并在需要时更正
  • 感谢提示,我更新了架构
  • 现在说得通了——看看答案:o)

标签: google-bigquery


【解决方案1】:

以下是 BigQuery 标准 SQL

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

【讨论】:

    猜你喜欢
    • 2015-08-14
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多