【问题标题】:Is it possible to UNNEST an array in BigQuery so that the nested data in split into columns by a key value?是否可以在 BigQuery 中取消嵌套数组,以便将嵌套数据按键值拆分为列?
【发布时间】:2019-05-20 15:02:54
【问题描述】:

假设我在 BigQuery 中有一些数据,其中包含一个嵌套的对象数组,如下所示:

{
    "name" : "Bob",
    "age": "24",
    "customFields": [
      {
        "index": "1",
        "value": "1.98"
      },
      {
        "index": "2",
        "value": "Nintendo"
      },
      {
        "index": "3",
        "value": "Yellow"
      }
    ]
}

我只能取消嵌套这些数据,以便“索引”和“值”字段成为列:

+------+-----+-------+----------+
| name | age | index |  value   |
+------+-----+-------+----------+
| Bob  |  24 |     1 | 1.98     |
| Bob  |  24 |     2 | Nintendo |
| Bob  |  24 |     3 | Yellow   |
+------+-----+-------+----------+

在大多数情况下,这将是所需的输出,但由于我使用的数据是指 Google Analytics(分析)自定义维度,因此我需要一些更复杂的东西。我正在尝试获取要在数据出现的列的名称中使用的索引值,如下所示:

+------+-----+---------+----------+---------+
| name | age | index_1 | index_2  | index_3 |
+------+-----+---------+----------+---------+
| Bob  |  24 |    1.98 | Nintendo | Yellow  |
+------+-----+---------+----------+---------+

这可能吗?生成此输出所需的 SQL 查询是什么?它应该在列名中使用“索引”值,因为输出不会一直处于有序的“1,2,3,...”中。

【问题讨论】:

    标签: google-bigquery


    【解决方案1】:

    您所描述的内容通常被称为数据透视表 - 一种将值用作列的转换。 SQL 通常不支持这一点,因为 SQL 是围绕具有固定架构的概念设计的,而数据透视表需要动态架构。

    但是,如果您有一组固定的索引列,则可以使用以下内容进行模拟:

    SELECT
      name,
      age,
      ARRAY(SELECT value FROM UNNEST(customFields) WHERE index="1")[SAFE_OFFSET(0)] AS index_1,
      ARRAY(SELECT value FROM UNNEST(customFields) WHERE index="2")[SAFE_OFFSET(0)] AS index_2,
      ARRAY(SELECT value FROM UNNEST(customFields) WHERE index="3")[SAFE_OFFSET(0)] AS index_3
    FROM your_table;
    

    这样做是专门为从 customFields 数组中挑选出正确值的每个索引定义列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 2014-09-11
      相关资源
      最近更新 更多