Given the following table:
CREATE TABLE table
(
"id" serial NOT NULL,
"timestamp" timestamp without time zone NOT NULL,
"count" integer NOT NULL DEFAULT 0
)
I am searching for "rare events". A rare event is a row that owns the following properties:
- Simple:
count = 1
- Hard: All rows within a 10 minute timespan (before and after the current row's timestamp) have
count = 0
(except the given row, of course).
Example:
id timestamp count
0 08:00 0
1 08:11 0
2 08:15 2 <== not rare event (count!=1)
3 08:19 0
4 08:24 0
5 08:25 0
6 08:29 1 <== not rare event (see 8:35)
7 08:31 0
8 08:35 1
9 08:40 0
10 08:46 1 <== rare event!
10 08:48 0
10 08:51 0
10 08:55 0
10 08:58 1 <== rare event!
10 09:02 0
10 09:09 1
Right now, I have the following PL/pgSQL-function:
SELECT curr.*
FROM gm_inductionloopdata curr
WHERE curr.count = 1
AND (
SELECT SUM(count)
FROM gm_inductionloopdata
WHERE timestamp BETWEEN curr.timestamp + '10 minutes'::INTERVAL
AND curr.timestamp - '10 minutes'::INTERVAL
)<2
which is dead slow. :-(
Any suggestions on how to improve performance? I am working on > 1 mio rows here and might need to find those "rare events" on a regular basis.