I donโt think you can do it cheaply with a simple query, CTE and window functions - their frame definition is static, but you need a dynamic frame .
Typically, you will need to carefully determine the lower and upper bounds of your window: The following queries exclude the current row and include the lower bound.
There is still a slight difference: the function includes previous peers of the current row, while the correlated subquery excludes them ...
Test case
Using ts instead of the reserved word date as the column name.
CREATE TEMP TABLE test ( id bigint ,ts timestamp );
Use CTE, aggregate timestamps in an array, ignore, count ...
That's right, performance deteriorates dramatically with a lot of rows filled with rows. There are several killers here. See below.
ARR - elements of the count array
I took a Roman request and tried to simplify it a bit:
- Remove the second CTE that is not needed.
- Convert 1st CTE to a subquery, which is faster.
- Direct count() instead of re-aggregating to an array and counting using array_length() .
But processing arrays is expensive, and performance is still poorly deteriorated with a lot of lines.
SELECT id, ts ,(SELECT count(*)::int - 1 FROM unnest(dates) x WHERE x >= sub.ts - interval '1h') AS ct FROM ( SELECT id, ts ,array_agg(ts) OVER(ORDER BY ts) AS dates FROM test ) sub;
COR - correlated subquery
You can solve this with a simple and ugly correlated subquery. Much faster, but still ...
SELECT id, ts ,(SELECT count(*) FROM test t1 WHERE t1.ts >= t.ts - interval '1h' AND t1.ts < t.ts) AS ct FROM test t ORDER BY ts;
FNC - Function
Iterate over the rows in chronological order using row_number() in the plpgsql function and combine this with the cursor on the same query, covering the required time interval. Then we can simply subtract the number of rows. It should be done beautifully.
CREATE OR REPLACE FUNCTION running_window_ct() RETURNS TABLE (id bigint, ts timestamp, ct int) AS $func$ DECLARE i CONSTANT interval = '1h';
Call:
SELECT * FROM running_window_ct();
SQL Fiddle
Benchmark
In the above table, I did a quick test on my old test server: PostgreSQL 9.1.9 on Debian).
-- TRUNCATE test; INSERT INTO test SELECT g, '2013-08-08'::timestamp + g * interval '5 min' + random() * 300 * interval '1 min' -- halfway realistic values FROM generate_series(1, 10000 ) g; CREATE INDEX test_ts_idx ON test (ts); ANALYZE test; -- temp table needs manual analyze
I changed the bold part for each run and took a maximum of 5 with EXPLAIN ANALYZE .
100 lines
ROM: 27.656 ms
ARR: 7.834 ms
COR: 5,488 ms
FNC: 1.115 ms
1000 lines
ROM: 2116.029 ms
ARR: 189.679 ms
COR: 65.802 ms
FNC: 8.466 ms
5000 lines
ROM: 51347 ms !!
ARR: 3167 ms
COR: 333 ms
FNC: 42 ms
100,000 lines
ROM: DNF
ARR: DNF
COR: 6760 ms
FNC: 828 ms
Function is the clear winner. This is fastest and an order of magnitude better. Array processing cannot compete.