sql - 如何返回最大滚动平均值的日期范围?
问题描述
我有以下查询:
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
希望我足够清楚。
谢谢 !
西蒙。
解决方案
#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
推荐阅读
- xcode - Apple TV 与 Xcode 12 配对
- python - Python 中的石头、纸和剪刀
- c - C程序返回带有答案的%
- r - R将虚拟变量转换为因子变量
- google-cloud-platform - 未找到 GKE Ingress 的 404
- javascript - 如何将自定义 Wordpress 字段传递到 mapbox-gl js 以在地图上创建标记?
- javascript - 编写一个接受单个数组参数的 javascript 函数
- javascript - 从 Blogger 导入不带标记的 JavaScript 文件
- css - ExtJS 7.x 布局动画上的现代网格选择错误
- c# - 寻找一种更优雅的方式通过表达式将 MethodInfo 转换为 Func