如何返回最大滚动平均值的日期范围?

时间:2018-07-04 21:16:31

标签: sql google-bigquery

我有以下查询:

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

希望我已经足够清楚了。

谢谢!

西蒙。

1 个答案:

答案 0 :(得分:2)

#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