0

I have a table something like this.

    
    count | date
    ------------------
     1     2012-01-01   
     4     2012-01-01   
     5     2012-01-02
    12     2012-01-03
     7     2012-01-04
     4     2012-01-05
    19     2012-01-06
     1     2012-01-07
     etc...

I'm looking for a way to calculate the average count per week over the previous 4 week period for each week.

The results should be something like...

    
    avg | yearweek
    ------------------
     3     201201   
     5     201202   
     6     201203
     1     201204
     11    201205
     3     201206
    18     201207
    12     201208
     etc...

...where each yearweek is the weekly average over the past 4 yearweeks.

Getting the weekly averages is simple enough but how do I then get that over the past 4 yearweeks? And then how to do I do that as a rolling average? Am I better off just doing this in code?

4

1 回答 1

0

虽然您当然可以在应用程序的代码中执行此操作,但如果您确实需要在 SQL 中执行此操作,您可以首先创建一个按周聚合的结果表,然后将其连接到自身以获得 4 周移动平均值。

这样做时,我不会存储平均值,而是存储总和和天数(一年中的第一周或最后一周可能没有 7 天——考虑边缘情况)。这样,当平均值的分母不同时,您将避免计算未加权平均值。

因此,假设您有一个表“weekly_results”,其中包含字段:yearweek、sumcount、numdays。您现在可以自行加入过去 4 周并获得总和和计数,然后从中计算平均值:

SELECT yearweek, sum_cnt/sum_dys as avg_moving_4wk
FROM (
    SELECT a.yearweek, sum(b.sumcount) as sum_cnt, sum(b.numdays) as sum_dys
    FROM weekly_results a
        join weekly_results b
        on a.yearweek - b.yearweek <4 and a.yearweek - b.yearweek >=0
    GROUP BY a.yearweek
) t1
GROUP BY yearweek
于 2012-07-25T01:55:40.623 回答