简体   繁体   English

缺少月份的 3 个月滚动平均值

[英]3 month rolling average with missing months

I've been reading the related questions here, and so far the solutions require that there are no missing months.我一直在这里阅读相关问题,到目前为止,解决方案要求没有丢失的月份。 Would love to get some help on what I can do if there are missing months?如果缺少几个月,我想得到一些帮助吗?

For example, I'd like to calculate the 3 month rolling average of orders per item.例如,我想计算每件商品的 3 个月滚动平均值。 If there is a missing month for an item, the calculation assumes that the number of orders for that item for that month is 0. If there are fewer than three months left, the rolling average isn't so important (it can be null or otherwise).如果某个项目缺少月份,则计算假定该项目该月的订单数量为 0。如果剩下的时间少于三个月,则滚动平均值并不那么重要(它可以是 null 或否则)。

MONTH   | ITEM | ORDERS | ROLLING_AVG
2021-04 | A    | 5      |  3.33
2021-04 | B    | 4      |  3
2021-03 | A    | 3      |  1.66
2021-03 | B    | 5      |  null
2021-02 | A    | 2      |  null
2021-01 | B    | 2      |  null

Big thanks in advance!提前非常感谢!

Also, is there a way to "add" the missing month rows without using a cross join with a list of items?此外,有没有一种方法可以“添加”缺少的月份行而不使用带有项目列表的交叉连接? For example if I have 10 million items, the cross join takes quite a while to execute.例如,如果我有 1000 万个项目,则执行交叉连接需要相当长的时间。

You can use a range window frame -- and some conditional logic:您可以使用range window 框架——以及一些条件逻辑:

select t.*,
       (case when min(month) over (partition by item) <= month - interval '2 month'
             then sum(orders) over (partition by item
                                    order by month
                                    range between interval '2 month' preceding and current row
                                   ) / 3.0
        end) as rolling_average
from t;

Here is a db<>fiddle. 是一个 db<>fiddle。 The results are slightly different from what is in your question, because there is not enough info for A in 2021-03 but there is enough for B in 2021-03.结果与您的问题略有不同,因为 2021-03 年 A 的信息不足,但 2021-03 年 B 的信息足够。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM