create table t (id int, date date, units int);
insert into t (id, date, units) values
(1, '2016-01-01', 1),
(2, '2016-01-02', 4),
(3, '2016-02-09', 6),
(4, '2016-03-01', 1),
(5, '2016-03-04', 2);
不清楚您是想要月份总计还是月份内的运行总计。当月总计:
select
id, date, units,
sum(units) over (partition by date_trunc('month', date)) as acumm
from t
order by 1,2
;
id | date | units | acumm
----+------------+-------+-------
1 | 2016-01-01 | 1 | 5
2 | 2016-01-02 | 4 | 5
3 | 2016-02-09 | 6 | 6
4 | 2016-03-01 | 1 | 3
5 | 2016-03-04 | 2 | 3
如果您想要一个月内的运行总计,则将 order by 添加到窗口函数:
select
id, date, units,
sum(units) over (
partition by date_trunc('month', date)
order by id
) as acumm
from t
order by 1,2
;
id | date | units | acumm
----+------------+-------+-------
1 | 2016-01-01 | 1 | 1
2 | 2016-01-02 | 4 | 5
3 | 2016-02-09 | 6 | 6
4 | 2016-03-01 | 1 | 1
5 | 2016-03-04 | 2 | 3