简体   繁体   中英

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.

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

In PostgreSQL 11 and above:

SELECT  SUM(value) OVER (ORDER BY tstamp RANGE '5 minute' PRECEDING) AS maxvalue,
        *
FROM    mytable m
ORDER BY
        maxvalue DESC
LIMIT   1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM