Postgres - 如何对每个x行窗口函数列的行进行求和?

时间:2018-03-23 18:10:01

标签: sql postgresql window-functions

我使用名为“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

正如您所看到的,总平均收入保持一致,因为它们每天应该有相同的金额。

对于正确方向的任何帮助都将不胜感激!

2 个答案:

答案 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

注意:

  • 7前期和当前行之间的距离实际上是 8 天而不是 7 天。我假设你想要7行。
  • 窗口子句(ROWS部分)确实需要ORDER BY
  • 对于您想要做的事情,我认为嵌套子查询最好。