首页 > 解决方案 > 如何返回最大滚动平均值的日期范围?

问题描述

我有以下查询:

SELECT account,
FLOOR(max(mov_avg_7d)) AS max_mov_avg_7d
FROM (
  SELECT account,date,items,
  AVG(items) OVER (PARTITION BY account ORDER BY date RANGE BETWEEN 6 PRECEDING AND CURRENT ROW) AS mov_avg_7d,
  FROM [my_table] 
)
group by account

这是我的表格示例:

Account         Date        Items
accountxxxxxx   2009-01-01  235
accountxxxxxx   2009-01-02  261
accountxxxxxx   2009-01-03  186
accountxxxxxx   2009-01-04  173
accountxxxxxx   2009-01-05  273
accountxxxxxx   2009-01-06  254
accountxxxxxx   2009-01-07  386

FLOOR(max(mov_avg_7d)) AS max_mov_avg_7d我能够检索到一个帐户在 7 天滚动期内可以拥有的最高平均项目数。

我希望能够为每个帐户提供与 7 天内最高平均项目数相关的日期范围(7 天)。

输出将是这样的:

Account        Date       Items   max_mov_avg_7d   min_date_range max_date_range     
accountxxxxxx  2009-01-01 235     635              2009-05-12     2009-05-19

希望我足够清楚。

谢谢 !

西蒙。

标签: sqlgoogle-bigquery

解决方案


#standardSQL
SELECT
  account,
  ARRAY_AGG(STRUCT(date, items, mov_avg_7d) ORDER BY mov_avg_7d DESC LIMIT 1)[OFFSET(0)].*
FROM (
  SELECT account,date,items,
  FLOOR(AVG(items) OVER (PARTITION BY account ORDER BY date RANGE BETWEEN 6 PRECEDING AND CURRENT ROW)) AS mov_avg_7d
  FROM `my_table`
)
group by account

推荐阅读