I have the following scenario in Postgres (I'm using 9.4.1).
I have a table of this format:
create table test(
id serial,
val numeric not null,
created timestamp not null default(current_timestamp),
fk integer not null
);
What I then have is a threshold numeric
field in another table which should be used to label each row of test
. For every value which is >= threshold
I want to have that record marked as true
but if it is true
it should reset subsequent counts to 0 at that point, e.g.
Data set:
insert into test(val, created, fk)
(100, now() + interval '10 minutes', 5),
(25, now() + interval '20 minutes', 5),
(30, now() + interval '30 minutes', 5),
(45, now() + interval '40 minutes', 5),
(10, now() + interval '50 minutes', 5);
With a threshold of 50 I would like to get the output as:
100 -> true (as 100 > 50) [reset]
25 -> false (as 25 < 50)
30 -> true (as 25 + 30 > 50) [reset]
45 -> false (as 45 < 50)
10 -> true (as 45 + 10 > 50)
Is it possible to do this in a single SQL query? So far I have experimented with using a window function.
select t.*,
sum(t.val) over (
partition by t.fk order by t.created
) as threshold_met
from test t
where t.fk = 5;
As you can see I have got it to the point where I have a cumulative frequency and suspect that the tweaking of rows between x preceding and current row
may be what I'm looking for. I just can't work out how to perform the reset, i.e. set x
, in the above to the appropriate value.