按子查询 Bigquery 分组并取平均值

Group by and average on subquery Bigquery

我正在尝试按日期对记录进行分组,并针对该特定日期获取称为延迟的列之一的平均值。我有以下标准 SQL 查询,该查询有效但在我尝试获取 table 的平均值和分组时不起作用:


SELECT * 
From 
(
SELECT 'ADS-B Average Latency for Asia' as metric_name, 'Daily' as metric_period_type,
  DATE(timestamp) as metric_date, collection_type, UNIX_SECONDS(ingestion_time) - UNIX_SECONDS(timestamp) as latency
  FROM `analytics.aoi_table` a
  order by metric_date
) table 

这是 table:

当我尝试使用下面的 sql 对上面的 table 进行平均和分组时,我收到以下错误:语法错误:应为“)”但在 [10 处获得了关键字 GROUP :3]

SQL 导致错误:

#standardSQL

SELECT * 
From 
(
SELECT 'ADS-B Average Latency for Asia' as metric_name,
  DATE(timestamp) as metric_date, collection_type, AVG(UNIX_SECONDS(ingestion_time) - UNIX_SECONDS(timestamp)) as latency
  FROM `ais-data-analysis.customer_analytics.itochu_aoi_table` a
  order by metric_date
  group by metric_date, collection_type
) table 


您的 group byorder by 顺序不对。此外,您不需要子查询:

select 'ADS-B Average Latency for Asia' as metric_name,
       DATE(timestamp) as metric_date, collection_type, AVG(UNIX_SECONDS(ingestion_time) - UNIX_SECONDS(timestamp)) as latency
from `ais-data-analysis.customer_analytics.itochu_aoi_table` a
group by metric_date, collection_type
order by metric_date

order by 子句在 group by 子句之后。此外,无需包装您的查询,您可以这样做:

SELECT 
    'ADS-B Average Latency for Asia' as metric_name,
    DATE(timestamp) as metric_date, 
    collection_type, 
    AVG(UNIX_SECONDS(ingestion_time) - UNIX_SECONDS(timestamp)) as latency
FROM `ais-data-analysis.customer_analytics.itochu_aoi_table` a
GROUP BY metric_date, collection_type
ORDER BY metric_date, collection_type