我无法在网上找到这个明确的例子。
根据这些数据,我想要过去2天的移动平均线:
create table expenses as (
select 'food' as expense, 5.0 as cost, current_date as date
union select 'food', 5.0, current_date - 1
union select 'food', 4.0, current_date - 2
union select 'food', 4.0, current_date - 3
union select 'food', 3.0, current_date - 4
union select 'food', 3.0, current_date - 5
union select 'entertainment', 9.0, current_date
union select 'entertainment', 9.0, current_date - 1
union select 'entertainment', 8.0, current_date - 2
union select 'entertainment', 8.0, current_date - 3
union select 'entertainment', 7.0, current_date - 4
union select 'entertainment', 7.0, current_date - 5
)
答案 0 :(得分:0)
这是我放在一起的解决方案
select
expense,
date,
cost,
avg(cost) over
(partition by expense order by date rows 2 preceding) as rolling_avg_cost
from expenses
给出了结果:
expense date cost rolling_avg_cost
entertainment Thursday, March 23, 2017 12:00 AM 7 7
entertainment Friday, March 24, 2017 12:00 AM 7 7
entertainment Saturday, March 25, 2017 12:00 AM 8 7.3
entertainment Sunday, March 26, 2017 12:00 AM 8 7.6
entertainment Monday, March 27, 2017 12:00 AM 9 8.3
entertainment Tuesday, March 28, 2017 12:00 AM 9 8.6
food Thursday, March 23, 2017 12:00 AM 3 3
food Friday, March 24, 2017 12:00 AM 3 3
food Saturday, March 25, 2017 12:00 AM 4 3.3
food Sunday, March 26, 2017 12:00 AM 4 3.6
food Monday, March 27, 2017 12:00 AM 5 4.3
food Tuesday, March 28, 2017 12:00 AM 5 4.6
可以看出,滚动平均值的窗口是当前行的3天(即当前行加上前两行,全部除以3)。