按子查询分组并按平均值进行分类Bigquery

时间:2020-01-08 14:09:17

标签: sql group-by google-bigquery average

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


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 

这是表: enter image description here

当我尝试使用下面的sql进行上表的平均值和分组时,出现以下错误:语法错误:预期为“)”,但关键字关键字GROUP在[10: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 


2 个答案:

答案 0 :(得分:1)

您的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

答案 1 :(得分:1)

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
相关问题