Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL中的滚动移动平均_Sql_Postgresql_Moving Average_Trading - Fatal编程技术网

SQL中的滚动移动平均

SQL中的滚动移动平均,sql,postgresql,moving-average,trading,Sql,Postgresql,Moving Average,Trading,我正在研究如何在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 这就得到了移动平均线的结果,但它也计算了

我正在研究如何在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行作为“null”,因为没有20行来计算平均值,并开始在n°20行获得平均值(如果我使用lag,则为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

我认为你可以简化逻辑:

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

嗨,戈登林诺夫。谢谢,案例陈述很有效。谢谢你关于简化逻辑的建议,但我实际上使用了一个移位参数,因为这个sma是一个使用移位参数的函数:)Hi@GordonLinoff。谢谢,案例陈述很有效。感谢您对简化逻辑的建议,但实际上我使用的是shift参数,因为此sma是一个使用shift参数的函数:)