【问题标题】:How to remove Repeated field in BigQuery schema?如何删除 BigQuery 架构中的重复字段?
【发布时间】:2019-08-21 06:08:36
【问题描述】:

我有一个架构,其中有一个重复字段嵌套到另一个重复字段中,如下所示:person.children.toys。我想让这个内部字段不重复(所以孩子只能有一个可为空的玩具)。我知道对于这样的更改,我需要使用新模式创建一个新表并运行 SQL 查询,将修改后的结果插入其中,但我不知道如何进行查询。我需要它为每个孩子选择第一个玩具(或 null)并将结果对象插入新表中。保证在源表中所有孩子的玩具不超过 1 个。

【问题讨论】:

    标签: sql google-cloud-platform google-bigquery


    【解决方案1】:

    以下是 BigQuery 标准 SQL

    我知道 - 它可能看起来过于复杂 - 但它完全保留了原始模式,同时消除了除第一个(或空)之外的所有玩具。如果您的真实架构不仅仅包含几个字段,那么这会很方便,因此您无需担心它们

    #standardSQL
    WITH `project.dataset.table` AS (
      SELECT 1 id, STRUCT([STRUCT('mike' AS name, ['woody'] AS toys)] AS children) AS person    UNION ALL
      SELECT 2 id, STRUCT([STRUCT('nik', ['buzz', 'bobeep']), ('john', ['car', 'buzz', 'bobeep'])] AS children) AS person   UNION ALL
      SELECT 3 id, STRUCT([STRUCT('vincent', IF(TRUE,[],['']))] AS children) AS person
    )
    SELECT * 
      REPLACE(
        (SELECT AS STRUCT * 
            REPLACE (
              (SELECT ARRAY_AGG(t) FROM
              (SELECT * REPLACE((SELECT toy FROM UNNEST(toys) toy WITH OFFSET ORDER BY OFFSET LIMIT 1) AS toys) FROM UNNEST(children)) t)
              AS children)
          FROM UNNEST([person]))
      AS person)
    FROM `project.dataset.table`     
    

    如果适用于以下数据

    Row id  person.children.name    person.children.toys     
    1   1   mike                    toy1     
    2   2   nik                     toy2     
                                    toy3     
            john                    toy4     
                                    toy5     
                                    toy6     
    3   3   vincent                
    

    结果将是

    Row id  person.children.name    person.children.toys     
    1   1   mike                    toy1     
    2   2   nik                     toy2     
            john                    toy4     
    3   3   vincent                 null       
    

    注意:最初的玩具字段 REPEATED STRING 变成了 STRING

    【讨论】:

      【解决方案2】:

      如果你有一个更好的描述架构,我可以给你一个更好的答案,但提供的数据:

      CREATE OR REPLACE TABLE `temp.flat` AS
      
      WITH data AS (
         SELECT 1 id, STRUCT([STRUCT(['woody']AS toy)] AS children) AS person
         UNION ALL
         SELECT 2 id, STRUCT([STRUCT(['buzz', 'bobeep'])] AS children) AS person
         UNION ALL
         SELECT 3 id, STRUCT([STRUCT(IF(true,[],['']))] AS children) AS person
      )
      
      SELECT id, person.children[SAFE_OFFSET(0)].toy[SAFE_OFFSET(0)] first_toy
      FROM `data`
      

      来自:

      收件人:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-28
        • 1970-01-01
        • 2013-03-24
        • 2016-05-26
        • 2015-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多