gpt4 book ai didi

sql - 在 SQL 中使用滞后函数查找移动平均线

转载 作者:行者123 更新时间:2023-12-02 17:38:20 26 4
gpt4 key购买 nike

我需要找到前 12 行的移动平均值。我需要让我的结果集看起来像这样。

t   Year    Month   Sales   MovingAverage
1 2010 3 20 NULL
2 2010 4 22 NULL
3 2010 5 24 NULL
4 2010 6 25 NULL
5 2010 7 23 NULL
6 2010 8 26 NULL
7 2010 9 28 NULL
8 2010 10 26 NULL
9 2010 11 29 NULL
10 2010 12 27 NULL
11 2011 1 28 NULL
12 2011 2 30 NULL
13 2011 3 27 25.67
14 2011 4 29 26.25
15 2011 5 26 26.83

对于第 13 行,我需要对第 1 行到第 12 行进行平均,并将结果返回到第 13 行的 MovingAverage 列中。第 1-12 行的 MovingAverage 为 NULL,因为应该至少有 12 行用于计算。行 t、Year、Month 和 Sales 已经存在。我需要创建 MovingAverage 行。我正在使用 postgreSQL,但语法应该非常相似。

最佳答案

不要使用 lag() 函数。有一个内置的移动平均函数。好吧,几乎:

select t.*, avg(sales) over (order by t range between 12 preceding and current row
from table t;

问题是这会产生前 11 个月的平均值。为了防止这种情况:

select t.*,
(case when row_number() over (order by t) >= 12
then avg(sales) over (order by t range between 12 preceding and current row
end) as MovingAvg
from table t;

请注意,对于此查询,语法 rows between 而不是 range between 非常相似。

关于sql - 在 SQL 中使用滞后函数查找移动平均线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24021819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com