Google bigquery 是否可以在BigQuery中取消数组的嵌套,以便按键值将中的嵌套数据拆分为列?
假设我在BigQuery中有一些数据,其中包括一个嵌套的对象数组,如下所示:Google bigquery 是否可以在BigQuery中取消数组的嵌套,以便按键值将中的嵌套数据拆分为列?,google-bigquery,Google Bigquery,假设我在BigQuery中有一些数据,其中包括一个嵌套的对象数组,如下所示: { "name" : "Bob", "age": "24", "customFields": [ { "index": "1", "value": "1.98" }, { "index": "2", "value": "Nintendo" }, { "ind
{
"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 |
+------+-----+-------+----------+
在大多数情况下,这将是理想的输出,但由于我使用的数据是指谷歌分析自定义维度,我需要一些更复杂的东西。我试图获取要在数据出现的列的名称中使用的索引值,如下所示:
+------+-----+---------+----------+---------+
| name | age | index_1 | index_2 | index_3 |
+------+-----+---------+----------+---------+
| Bob | 24 | 1.98 | Nintendo | Yellow |
+------+-----+---------+----------+---------+
这可能吗?生成此输出需要什么SQL查询?它应该在列名中使用“index”值,因为输出不会一直按“1,2,3,…”的顺序排列。您所描述的通常被称为透视表-一种将值用作列的转换。SQL通常不支持这一点,因为SQL是围绕拥有固定模式的概念设计的,而pivot表需要动态模式 但是,如果您有一组固定的索引列,则可以使用以下内容模拟它:
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数组中选择正确值的每个索引专门定义列