由过去7天限制的分区平均值

时间:2017-05-31 16:04:33

标签: sql vertica

我有一个跨越过去30天的查询,它总计了总收入,但我也想要最近30天的总和,加上过去7天的平均值。我想要这样的东西:

select 
    country 
    , avg(revenue) over (partition by country range between current_date - 7 and current_date) avg_revenue_last_7_days
    , sum(revenue) total_revenue_30_days
from table 
group by 1,2

是否可以获得比聚合所基于的更少天数的平均值?

我想避免使用子查询,因为查询已经很复杂了。

1 个答案:

答案 0 :(得分:1)

您不需要窗口函数,只需要条件聚合:

select country,
       avg(case when datecol between current_date - 7 and current_date
                then revenue
           end) as avg_revenue_last_7_days,
       sum(case when datecol between current_date - 30 and current_date
                then revenue
           end) as total_revenue_30_days
from table 
group by country;