在MySQL中使用窗口函数移动平均 [英] Moving average using window function in MySQL

查看:435
本文介绍了在MySQL中使用窗口函数移动平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据集如下:

Date              Price     3 Day Moving Average
-------------------------------------------------
2018-08-01         10        
2018-08-02         12       
2018-08-03         11        11    (10+12+11)/3\n
2018-08-04         15        12.67 (12+11+15)/3
2018-08-05         13        13    (11+15+13)/3
2018-08-06         17         ...
2018-08-07         18         …
2018-08-08         20         ..

仅使用MySQL窗口函数是否有可能?

Is this possible using just MySQL window functions?

服务器版本:8.0.12 MySQL社区服务器-GPL

Server version: 8.0.12 MySQL Community Server - GPL

推荐答案

您可以使用

DB小提琴演示

详细信息:

  • 2 PRECEDING表示当前行上方的两行(当前行除外).我们在Date上显式定义升序.因此,这意味着两个最接近的日期,低于当前行的日期
  • CURRENT ROW表示当前行.
  • BETWEEN使我们能够考虑定义范围内的行(包括边界条件).
  • 此后,您要将移动均线移至对于前两行为null,我们可以使用 Case .. When
  • 2 PRECEDING means two rows above the current row (excluding the current row). We explicitly define Ascending order on Date. So that would means two closest dates, lower than the current row's date
  • CURRENT ROW means the current row.
  • BETWEEN allows us to consider the rows in the defined range (including boundary conditions).
  • Since, you want moving average to be null for the first two rows, we can check for this using Row_number() function in Case .. When

这篇关于在MySQL中使用窗口函数移动平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆