如何从标准 SQL 中的数组结构返回结构数组?

Jac*_*ins 2 struct google-bigquery array-agg

我的表上有一个我想要访问的非重复记录列。在此记录中,有几个重复的值。

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

STRUCT<item ARRAY<STRING> unit_cost ARRAY<INT64> quantity ARRAY<INT64>> as costs
Run Code Online (Sandbox Code Playgroud)

例如。数据可能代表:

item ['cheese', 'ham', 'salad']
unit_cost [2, 5, 8]
quantity [1, 2, 1]
Run Code Online (Sandbox Code Playgroud)

所以我想将其作为更好的数据结构(结构数组)返回:

[
  {'item': 'cheese', 'unit_cost': 2, 'quantity': 1}, 
  {'item': 'ham', 'unit_cost': 5, 'quantity': 2}
  {'item': 'salad', 'unit_cost': 8, 'quantity': 1}
]
Run Code Online (Sandbox Code Playgroud)

我试过:

SELECT ARRAY_AGG(costs)
Run Code Online (Sandbox Code Playgroud)

但这会导致

            [
              {
                "item": ['cheese', 'ham', 'salad'],
                "unit_cost": [2, 5, 8],
                "quantity": [1, 2, 1]
              }
            ]
Run Code Online (Sandbox Code Playgroud)

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

是否可以在这里巧妙地使用标准 SQL从 a STRUCTof multipleARRAY变为 an ARRAYof multiple ?STRUCT

Mik*_*ant 6

以下是 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`   
Run Code Online (Sandbox Code Playgroud)

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

[
  {
    "costs": [
      {
        "item": "cheese",
        "unit_cost": "2",
        "quantity": "1"
      },
      {
        "item": "ham",
        "unit_cost": "5",
        "quantity": "2"
      },
      {
        "item": "salad",
        "unit_cost": "8",
        "quantity": "1"
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)