简体   繁体   English

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

[英]How do I return the date range of a max rolling average value?

I have the following query : 我有以下查询:

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

Here is a sample of my table : 这是我桌子的样品:

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

With FLOOR(max(mov_avg_7d)) AS max_mov_avg_7d I'm able to retrieve the highest average number of Items an account can have over a 7 day rolling period. 使用FLOOR(max(mov_avg_7d)) AS max_mov_avg_7d我可以检索一个帐户在7天的滚动期内可以拥有的平均最高物品数。

I would like to be able to have for each account the date range (7 days) associated with the highest average number of Items over 7 days. 我希望每个帐户都可以拥有与7天内平均商品数最高相关的日期范围(7天)。

Output would be something like this : 输出将是这样的:

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

Hopefully, I'm clear enough. 希望我已经足够清楚了。

Thanks ! 谢谢 !

Simon. 西蒙

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 SQL 返回日期范围内一天的平均值? - How do I use SQL to return an average value for a day in a date range? 如何查询最大值和找到的返回日期 - How do I query for a max value and return date found 如何使用MAX()返回具有最大值的行? - How do I use MAX() to return the row that has the max value? 查询返回日期范围中的行但仅返回列的最大值 - Query to return rows in date range but return only max value of column 如何在SQL中的滚动日期范围内标识记录的MIN值 - How to identify MIN value for records within a rolling date range in SQL 如何返回日期范围> = 2天的结果? - How do I return results of a date range of >=2 days? 如何获得某个值的最大日期和阶段名称? - How do I get the max date and stage name for a certain value? 如何在 MySQL 8 中使用两个变量进行滚动平均? - How to do a rolling average in MySQL 8 with two variables? 如何根据最小日期行中的条件返回最大日期结果? - How do I return a max date results against criteria in a min date row? 如何在 oracle 中找到具有日期数据类型的特定列的平均值? 我希望平均值为 NUMBER 数据类型 - How do i find the average value of a particular column which has date datatype in oracle? And i want the average to be NUMBER datatype
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM