SET search_path=tmp;
DROP TABLE zdates;
CREATE TABLE zdates
( zdate timestamp NOT NULL PRIMARY KEY
, val INTEGER NOT NULL
);
-- some data
INSERT INTO zdates(zdate,val)
SELECT s, 0
FROM generate_series('2012-01-01', '2012-12-31', '1 day'::interval ) s
;
UPDATE zdates
SET val = 1000 * random();
DELETE FROM zdates
WHERE random() < 0.1;
-- CTE to round the intervals down/up to the begin/end of the month
WITH zope AS (
SELECT date_trunc('month', zdate)::date AS zbegin
, date_trunc('month', zdate+interval '1 month')::date AS zend
, val AS val
FROM zdates
)
SELECT z.zbegin
, z.zend
, COUNT(*) AS zcount
, SUM(val) AS zval
FROM zope z
GROUP BY z.zbegin, z.zend
ORDER BY z.zbegin, z.zend
;
结果:
CREATE TABLE
INSERT 0 366
UPDATE 366
DELETE 52
zbegin | zend | zcount | zval
------------+------------+--------+-------
2012-01-01 | 2012-02-01 | 28 | 13740
2012-02-01 | 2012-03-01 | 28 | 14923
2012-03-01 | 2012-04-01 | 26 | 13775
2012-04-01 | 2012-05-01 | 25 | 11880
2012-05-01 | 2012-06-01 | 25 | 12693
2012-06-01 | 2012-07-01 | 25 | 11082
2012-07-01 | 2012-08-01 | 26 | 13254
2012-08-01 | 2012-09-01 | 28 | 13632
2012-09-01 | 2012-10-01 | 28 | 16461
2012-10-01 | 2012-11-01 | 23 | 12622
2012-11-01 | 2012-12-01 | 24 | 12554
2012-12-01 | 2013-01-01 | 28 | 14563
(12 rows)