jasonmclose jasonmclose - 5 months ago 29
SQL Question

sql sliding window - finding max value over interval

i have a sliding window problem. specifically, i do not know where my window should start and where it should end. i do know the size of my interval/window.

i need to find the start/end of the window that delivers the best (or worst, depending on how you look at it) case scenario.

here is an example dataset:

value | tstamp
100 | 2013-02-20 00:01:00
200 | 2013-02-20 00:02:00
300 | 2013-02-20 00:03:00
400 | 2013-02-20 00:04:00
500 | 2013-02-20 00:05:00
600 | 2013-02-20 00:06:00
500 | 2013-02-20 00:07:00
400 | 2013-02-20 00:08:00
300 | 2013-02-20 00:09:00
200 | 2013-02-20 00:10:00
100 | 2013-02-20 00:11:00


let's say i know that my interval needs to be 5 minutes. so, i need to know the value and timestamps included in the 5 minute interval where the sum of 'value' is the highest. in my above example, the rows from '2013-02-20 00:04:00' to '2013-02-20 00:08:00' would give me a sum of 400+500+600+500+400 = 2400, which is the highest value over 5 minutes in that table.

i'm not opposed to using multiple tables if needed. but i'm trying to find a "best case scenario" interval. results can go either way, as long as they net the interval. if i get all data points over that interval, it still works. if i get the start and end points, i can use those as well.

i've found several sliding window problems for SQL, but haven't found any where the window size is the known factor, and the starting point is unknown.

Answer
SELECT  *,
        (
        SELECT  SUM(value)
        FROM    mytable mi
        WHERE   mi.tstamp BETWEEN m.tstamp - '2.5 minute'::INTERVAL AND m.tstamp + '2.5 minute'::INTERVAL
        ) AS maxvalue
FROM    mytable m
ORDER BY
        maxvalue DESC
LIMIT   1