我使用一个名为“avg_rev”的窗口函数创建了一个列,它给出了过去7天按销售地区列出的平均收入金额,使用:

AVG(rev) OVER (PARTITION BY sales_region ROWS BETWEEN 7 PRECEDING AND CURRENT ROW) AS avg_rev

我想把每个销售地区每天的平均收入加起来。下表:
date     | sales_region | rev    | avg_rev
---------|--------------|--------|---------
01-23-18 | US East      | 192643 | 187463
01-23-18 | US South     | 89734  | 90245
01-23-18 | US West      | 254867 | 270974
01-24-18 | US East      | 168903 | 189245
01-24-18 | US South     | 93127  | 90621
01-24-18 | US West      | 252075 | 269874

我想要另一列显示每天的总平均收入,方法是将最后3行相加(或以任何其他方式得到相同的结果),以便得到下表:
date     | sales_region | rev    | avg_rev | total_avg
---------|--------------|--------|---------|-----------
01-23-18 | US East      | 192643 | 187463  | 548682
01-23-18 | US South     | 89734  | 90245   | 548682
01-23-18 | US West      | 254867 | 270974  | 548682
01-24-18 | US East      | 168903 | 189245  | 550740
01-24-18 | US South     | 93127  | 91621   | 550740
01-24-18 | US West      | 252075 | 269874  | 550740

正如你所看到的,平均总收入保持一致,因为他们每天应该有相同的总和。
如果您能提供正确的帮助,我们将不胜感激!

最佳答案

使用SUM聚合该值,并包含在group by中选择的所有其他列。

select date,sales_region,rev
,AVG(rev) OVER (PARTITION BY sales_region ROWS BETWEEN 7 PRECEDING AND CURRENT ROW) AS avg_rev
,SUM(AVG(rev)) OVER (PARTITION BY sales_region ROWS BETWEEN 7 PRECEDING AND CURRENT ROW) AS avg_sum
from tbl
group by date,sales_region,rev

10-04 14:57