【问题标题】:Using the lag function to find a moving average in SQL使用滞后函数在 SQL 中查找移动平均线
【发布时间】:2014-06-03 17:52:12
【问题描述】:

我需要找到前 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,但语法应该非常相似。

【问题讨论】:

    标签: sql


    【解决方案1】:

    不要使用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 将非常相似。

    【讨论】:

    • 除了第二个,您还可以:select t.*, avg(sales) over (order by t range between 12 preceding and 1 preceding) as MovingAvg from table t;
    • @SunnyPatel 。 . .如果没有 12 个值,则 OP 明确希望值为 NULL。这就是为什么这个答案使用case 表达式。
    猜你喜欢
    • 2012-11-19
    • 1970-01-01
    • 2021-06-14
    • 2012-05-24
    • 2021-08-13
    • 2023-04-07
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    相关资源
    最近更新 更多