[英]BigQuery - Add elements from array into array of structs
我有一個看起來像這樣的結構:
{"event": {
"timestamp": [
"2019-01-13 17:21:08.570140 UTC",
"2019-01-14 14:10:55.475515 UTC",
"2019-01-09 14:02:51.848917 UTC"
],
"properties": [
{"device_model": "iPhone", "country": "United Kingdom"},
{"device_model": "Android", "country": "United States"},
{"device_model": "iPhone", "country": "Sweden"}
]
}
我想實現這一點:讓每個時間戳進入相應的結構。
{"event": [
{"timestamp": "2019-01-13 17:21:08.570140 UTC","device_model":
"iPhone", "country": "United Kingdom"},
{"timestamp": "2019-01-14 14:10:55.475515 UTC", "device_model":
"Android", "country": "United States"},
{"timestamp": "2019-01-09 14:02:51.848917 UTC", "device_model":
"iPhone", "country": "Sweden"}
]
}
我從這樣的查詢創建了當前結構:
WITH
events AS (
SELECT
"customer_1" AS customer_id,
"timestamp_1" AS timestamp,
STRUCT("iphone" AS device_model,
"uk" AS country ) AS properties
UNION ALL
SELECT
"customer_2" AS customer_id,
"timestamp_2" AS timestamp,
STRUCT("android" AS device_model,
"us" AS country) AS properties
UNION ALL
SELECT
"customer_2" AS customer_id,
"timestamp_3" AS timestamp,
STRUCT("iphone" AS device_model,
"sweden" AS country) AS properties )
SELECT
customer_id,
STRUCT(ARRAY_AGG(timestamp) AS timestamp,
ARRAY_AGG(properties) AS properties) AS event
FROM
events
GROUP BY
customer_id
如何修改查詢以獲得所需的結構?
- - 編輯
我可以這樣做,但這需要在我生成查詢時知道屬性的模式 - 這是可能的,但不是很漂亮。 有沒有更簡單的方法?
WITH
events AS (
SELECT
"customer_1" AS customer_id,
"timestamp_1" AS timestamp,
STRUCT("iphone" AS device_model,
"uk" AS country ) AS properties
UNION ALL
SELECT
"customer_2" AS customer_id,
"timestamp_2" AS timestamp,
STRUCT("android" AS device_model,
"us" AS country) AS properties
UNION ALL
SELECT
"customer_2" AS customer_id,
"timestamp_3" AS timestamp,
STRUCT("iphone" AS device_model,
"sweden" AS country) AS properties )
SELECT
customer_id,
ARRAY_AGG(properties) AS event
FROM (
SELECT
customer_id,
struct(timestamp as timestamp,
properties.device_model as device_model,
properties.country as country) as properties
FROM
events)
GROUP BY
customer_id
您可以利用SELECT AS STRUCT
並使用properties
作為選擇器來做這樣的事情。
SELECT
customer_id,
ARRAY_AGG(properties) AS prop
FROM (
SELECT
customer_id,
(
SELECT
AS STRUCT timestamp,
properties.*) AS properties
FROM
events e )
GROUP BY
1
這將返回:
[
{
"customer_id": "customer_1",
"prop": [
{
"timestamp": "timestamp_1",
"device_model": "iphone",
"country": "uk"
}
]
},
{
"customer_id": "customer_2",
"prop": [
{
"timestamp": "timestamp_2",
"device_model": "android",
"country": "us"
},
{
"timestamp": "timestamp_3",
"device_model": "iphone",
"country": "sweden"
}
]
}
]
你可以進一步寫下這樣的文章:
SELECT AS STRUCT e.* except(customer_id)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.