我使用名为“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
正如您所看到的,总平均收入保持一致,因为它们每天应该有相同的金额。
对于正确方向的任何帮助都将不胜感激!
答案 0 :(得分:1)
使用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
答案 1 :(得分:0)
如果我真的不得不猜测你想要什么,那就像是:
SELECT t.*,
SUM(avg_rev_7day) OVER (PARTITION BY date)
FROM (SELECT AVG(rev) OVER (PARTITION BY sales_region
ORDER BY date
ROWS BETWEEN 7 PRECEDING AND 1 PRECENDING
) AS avg_rev_7day,
. . .
) t
注意:
ROWS
部分)确实需要ORDER BY
。