2017-05-31 89 views
0

我有一個跨越最近30天的查詢,它總計總收入,但是我還想要連同過去30天的總和,加上最近7天的平均值。我想要這樣的事情:最近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 

是否有可能獲得比聚合基於的更少的天數的平均數?

我想避免子查詢,因爲查詢已經相當複雜。

+0

你怎麼能GROUP BY 2?並且不要標記不相關的產品。 – Strawberry

+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; 
+0

...並且我會添加'WHERE datecol> = CURRENT_DATE - 30'以最小化行到GROUP BY ... – marcothesane