在BigQuery中使用STRUCT类型进行聚合操作。
假设我们有一个包含以下列的表:
CREATE TABLE my_table (
id INT64,
device STRING,
event_timestamp TIMESTAMP,
event_data STRUCT
);
要按设备汇总计算foo和bar的平均值,我们可以使用以下查询:
SELECT
device,
AVG(event_data.foo) AS avg_foo,
AVG(event_data.bar) AS avg_bar
FROM
my_table
GROUP BY
device;
此查询将返回一个表,其中每个设备都有一个平均foo和一个平均bar值。这些值存储在STRUCT类型中,可以使用"."运算符访问。
注意,在使用STRUCT类型进行聚合操作时,每个STRUCT字段都需要单独处理。在上面的示例中,我们分别计算了事件数据中的每个字段的平均值。
完整示例代码如下:
CREATE TABLE my_table (
id INT64,
device STRING,
event_timestamp TIMESTAMP,
event_data STRUCT
);
INSERT INTO my_table VALUES
(1, 'device1', TIMESTAMP '2022-01-01 00:00:00', STRUCT(10, 'hello')),
(2, 'device2', TIMESTAMP '2022-01-02 00:00:00', STRUCT(20, 'world')),
(3, 'device1', TIMESTAMP '2022-01-03 00:00:00', STRUCT(30, 'foo')),
(4, 'device2', TIMESTAMP '2022-01-04 00:00:00', STRUCT(40, 'bar'));
SELECT
device,
AVG(event_data.foo) AS avg_foo,
AVG(event_data.bar) AS avg_bar
FROM
my_table
GROUP BY
device;