【发布时间】:2018-06-17 09:20:05
【问题描述】:
这是我的示例数据(表“sumtest”):
+-------+--------+-------+
| month | value | year |
+-------+--------+-------+
| 1 | 10 | 2017 |
| 2 | 0 | 2017 |
| 2 | 10 | 2016 | # note: different year
| 2 | 5 | 2017 |
| 3 | 88 | 2017 |
| 3 | 2 | 2017 |
| 5 | 1 | 2017 |
| 5 | 4 | 2017 |
| 5 | 5 | 2017 |
+-------+--------+-------+
我想获得每个月的总值,以及该特定月份每年的运行总值,即我希望我的结果是这样的:
+------+-------+-----------+----------+
| year | month | sum_month | sum_year |
+------+-------+-----------+----------+
| 2016 | 2 | 10 | 10 |
| 2017 | 1 | 10 | 10 |
| 2017 | 2 | 5 | 15 |
| 2017 | 3 | 90 | 105 |
| 2017 | 5 | 10 | 115 |
+------+-------+-----------+----------+
我是 Postgres 的新手,我尝试了以下方法:
SELECT *, sum(value) OVER (PARTITION BY month, year) AS sum_month,
sum(value) OVER (PARTITION BY year) AS sum_year
FROM sumtest
ORDER BY year, month
但这会为每个原始条目生成一行,并且每行列出的年度总和而不是到目前为止的累积总和:
+-------+-------+------+-----------+----------+
| month | value | year | sum_month | sum_year |
+-------+-------+------+-----------+----------+
| 2 | 10 | 2016 | '10' | '10' |
| 1 | 10 | 2017 | '10' | '115' |
| 2 | 5 | 2017 | '5' | '115' |
| 2 | 0 | 2017 | '5' | '115' |
| 3 | 2 | 2017 | '90' | '115' |
| 3 | 88 | 2017 | '90' | '115' |
| 5 | 4 | 2017 | '10' | '115' |
| 5 | 1 | 2017 | '10' | '115' |
| 5 | 5 | 2017 | '10' | '115' |
+-------+-------+------+-----------+----------+
我也尝试过使用 GROUP BY,它适用于月份的累积总和,但我现在没有如何包括一年的运行总计(因为不应该按月份分组)。
任何帮助将不胜感激。
【问题讨论】:
-
@Andrew 这个问题是我从哪里得到 PARTITION BY 语句的,但我也需要分组。
标签: sql postgresql window-functions cumulative-sum