BigQuery UNNEST 导致重复的列名

BigQuery UNNEST causing duplicate column names

我正在尝试创建一个视图,其中包括取消嵌套 BigQuery 中名为 customers 的 table 中的某些值。 JSON 格式的一行客户 table 的示例如下所示:

{
    "customer_id": "12345",
    "created_date": "2020-12-20",
    "customer_purchases": [
        {
            "created_date": "2020-12-20",
            "item_id": 100
        }
    ]
}

我想要这样的视图,其中每一行都是客户购买的,并且列与客户 table 中的列完全相同。因此,我取消嵌套客户购买如下:

SELECT
  *
FROM `sales.customers`,
UNNEST (customer_purchases)

但是我现在收到一个错误:

Duplicate column name 'created_date' in definition of view 'sales.customers_purchases_view'

我可以创建一个巨大的查询,在其中重命名所有重复的字段,但这并不理想,而且很难持续维护。视图是否可以为任何未嵌套的列添加前缀或其他内容?

我通常会这样写:

SELECT c.* except (customer_purchases), purchase
FROM `sales.customers` c UNNEST
     (customer_purchases) purchase;

这会将购买作为结构放入结果集中。

您还可以删除和重命名名称:

如果您想要单独的列,您可以重命名它们:

SELECT c.* except (customer_purchases, created_date),
       c.created_date as customer_created_date,
       purchase.*
FROM `sales.customers` c UNNEST
     (customer_purchases) purchase;

或者:

SELECT c.* except (customer_purchases),
       purchase.* except (created_date)
       purchase.created_date as purchase_created_date
FROM `sales.customers` c UNNEST
     (customer_purchases) purchase;

我相信这很简单:

SELECT
  a.*
FROM `sales.customers` AS a
CROSS JOIN UNNEST(customer_purchases)