2017-03-28 91 views
0

我找不到這個在線的明確示例。PostgreSQL分組滾動平均值(用於多個標籤)

我想基於這個數據,在過去的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

下面是解我放在一起

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)。