@vyegorov's answer covers it mostly. But I have more problems than in the comments.
Do not use reserved words such as date
and count
as identifiers at all. PostgreSQL allows these two keywords as an identifier - except for every SQL standard. But this is still bad practice. The fact that you can use anything inside double quotes as an identifier, even "; DELETE FROM tbl;"
doesn't make him a good idea. The name "date"
for a timestamp
is misleading.
Invalid data type. The example displays timestamp
, not timestamptz
. It does not matter here, but is still misleading.
You do not need COALESCE()
. Using the lag()
and lead()
functions, you can specify the default value as the third parameter:
Based on this setting:
CREATE TABLE tbl (ts timestamp, ct int4); INSERT INTO tbl VALUES ('2012-06-21 05:20:00', 12) , ('2012-06-21 05:21:00', 14) , ('2012-06-21 05:22:00', 10) , ('2012-06-21 05:23:00', 20) , ('2012-06-21 05:24:00', 25) , ('2012-06-21 05:25:00', 30) , ('2012-06-21 05:26:00', 10);
Query:
SELECT ts, ct + lag(ct, 1, 0) OVER (ORDER BY ts) + lag(ct, 2, 0) OVER (ORDER BY ts) AS total FROM tbl;
Or better : use one sum()
as a window aggregation function with a custom window frame :
SELECT ts, sum(ct) OVER (ORDER BY ts ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) FROM tbl;
The same result.
Connected:
source share