1

我的表上有一个不重复的记录列,我想访问它。在这个记录上,有几个重复的值。

所以它是一个RECORD,就像这样:

STRUCT<item ARRAY<STRING> unit_cost ARRAY<INT64> quantity ARRAY<INT64>> as costs

例如。数据可能代表:

item ['cheese', 'ham', 'salad']
unit_cost [2, 5, 8]
quantity [1, 2, 1]

所以我想把它作为一个更好的数据结构返回,一个结构数组:

[
  {'item': 'cheese', 'unit_cost': 2, 'quantity': 1}, 
  {'item': 'ham', 'unit_cost': 5, 'quantity': 2}
  {'item': 'salad', 'unit_cost': 8, 'quantity': 1}
]

我试过了:

SELECT ARRAY_AGG(costs)

但它导致

            [
              {
                "item": ['cheese', 'ham', 'salad'],
                "unit_cost": [2, 5, 8],
                "quantity": [1, 2, 1]
              }
            ]

这不是我期望它返回的结果。

是否可以在这里巧妙地使用标准 SQL从STRUCT多个ARRAY变为ARRAY多个?STRUCT

4

2 回答 2

3

以下是 BigQuery 标准 SQL

#standardSQL
SELECT 
  ARRAY(
    SELECT AS STRUCT item, unit_cost, quantity
    FROM UNNEST(costs.item) item WITH OFFSET
    LEFT JOIN UNNEST(costs.unit_cost) unit_cost WITH OFFSET USING(OFFSET)
    LEFT JOIN UNNEST(costs.quantity) quantity WITH OFFSET USING(OFFSET)
  ) AS costs
FROM `project.dataset.table`   

如果适用于您的问题的样本数据 - 结果是(在 JSON 视图中)

[
  {
    "costs": [
      {
        "item": "cheese",
        "unit_cost": "2",
        "quantity": "1"
      },
      {
        "item": "ham",
        "unit_cost": "5",
        "quantity": "2"
      },
      {
        "item": "salad",
        "unit_cost": "8",
        "quantity": "1"
      }
    ]
  }
]
于 2019-10-04T19:05:26.880 回答
1

您可以使用以下查询:

with data as (
select STRUCT<item ARRAY<STRING>, unit_cost ARRAY<INT64>, quantity ARRAY<INT64>>
  (['cheese', 'ham', 'salad'], [2, 5, 8], [1, 2, 1]) entry
union all
select (['othercheese', 'otherham', 'othersalad'], [3, 8, 10], [11, 22, 11])
union all
select (['othercheese', 'otherham', 'othersalad'], [3, 8, 10], [11, 22, 11])
) 
SELECT ARRAY_AGG(STRUCT(item, unit_cost, quantity))
FROM data, UNNEST(entry.item) item WITH OFFSET
    LEFT JOIN UNNEST(entry.unit_cost) unit_cost WITH OFFSET USING(OFFSET)
    LEFT JOIN UNNEST(entry.quantity) quantity WITH OFFSET USING(OFFSET)

输出

[
  {
    "f0_": [
      {
        "item": "cheese",
        "unit_cost": "2",
        "quantity": "1"
      },
      {
        "item": "ham",
        "unit_cost": "5",
        "quantity": "2"
      },
      {
        "item": "salad",
        "unit_cost": "8",
        "quantity": "1"
      },
      {
        "item": "othercheese",
        "unit_cost": "3",
        "quantity": "11"
      },
      {
        "item": "otherham",
        "unit_cost": "8",
        "quantity": "22"
      },
      {
        "item": "othersalad",
        "unit_cost": "10",
        "quantity": "11"
      },
      {
        "item": "othercheese",
        "unit_cost": "3",
        "quantity": "11"
      },
      {
        "item": "otherham",
        "unit_cost": "8",
        "quantity": "22"
      },
      {
        "item": "othersalad",
        "unit_cost": "10",
        "quantity": "11"
      }
    ]
  }
]
于 2019-10-04T19:21:45.613 回答