[英]rolling moving average in 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
:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.