sql - SQL中的滚动移动平均线
问题描述
我正在寻找如何在 postgresql 中做移动平均线。我已经做的是:
with sma as (
select date,
avg(col) over(order by date rows between 20 preceding and current row) mov_avg
from eurusd_ohlc
)
select date, lag(mov_avg,1) over(order by date) from sma
这会产生移动平均线的结果,但即使没有足够的项来计算 20 周期移动平均线,它也会计算值。我得到的结果如下:
-----------------------------------------------------
| date | sma |
|2020-02-20 03:27:35.140751| NULL |
|2020-02-20 04:19:17.088462| 1.07966 |
|2020-02-20 05:54:44.060929| 1.0796299999999999 |
|2020-02-20 06:41:32.916934| 1.07964 |
|2020-02-20 07:11:59.667919| 1.0794899999999998 |
|2020-02-20 07:26:06.342439| 1.07938 |
|2020-02-20 07:44:15.313053| 1.0792033333333333 |
|2020-02-20 08:06:31.498739| 1.0791971428571427 |
|2020-02-20 08:26:12.278109| 1.07920625 |
|2020-02-20 08:50:23.925312| 1.079178888888889 |
|2020-02-20 09:14:48.951868| 1.079202 |
虽然这是正确的,因为它用 1、2、3 和一直到 20 个值计算平均值,然后它实际上收敛,我希望前 20 行作为“空值”,因为没有 20行来计算平均值并开始在第 20 行(如果我使用滞后,则为 21)中获取平均值。
我怎样才能做到这一点?
解决方案
我认为您可以简化逻辑:
select date, avg(col) over (order by date rows between 21 preceding and 1 preceding)
from eurusd_ohlc
使用case
表达式获取null
s:
select date,
(case when row_number() over (order by date) >= 21
then avg(col) over (order by date rows between 21 preceding and 1 preceding)
end) as mov_avg
from eurusd_ohlc
推荐阅读
- c# - 在以下场景中,如何将自定义对象映射到相应的任务?
- excel - 仅使用 vba 的索引匹配过滤数据
- javascript - 如何防止反应表排序和搜索重置
- neo4j - 计算 Neo4j 中每个元素的列表值的平均值
- android - 如果可能的话,填充空格的动态 TextView
- android - 发现无效的 Gradle JDK 配置。打开 Gradle 设置
- .net - .Net Framework 项目是否会成为 .Net 5 的跨平台?
- javascript - 加载 JSON 适用于 XMLHttpRequest 但不适用于 jQuery
- function - java调用存储在集合中的参数的函数
- vba - 系统管理员无法发送 olBCC 邮件