Retrieve aggregates for arbitrary time intervals

后端 未结 1 1396
独厮守ぢ
独厮守ぢ 2020-12-17 05:25

This is the query I have so far, to create daily bars:

SELECT DISTINCT date_trunc(\'hour\',t) AS date,
min(price) OVER w,
max(price) OVER w,
first_value(pric         


        
相关标签:
1条回答
  • For 15-minute intervals, building on your example:

    SELECT DISTINCT
         , date_trunc('hour', t) AS h
         , floor(EXTRACT(minute FROM t) / 15) AS m15
         , min(price) OVER w
         , max(price) OVER w
         , first_value(price) OVER w
         , last_value(price) OVER w
    FROM   ticker
    WINDOW w AS (PARTITION BY date_trunc('hour', t)
                            , floor(extract(minute FROM t) / 15));
    

    Works for 5 minutes, too.


    A more generic solution for any regular time intervals, across any period of time:

    WITH x AS (
        SELECT t1, t1 + interval '5min' AS t2
        FROM   generate_series(timestamp '2012-07-18 00:00'
                             , timestamp '2012-07-18 23:55'
                             , interval '5 min') AS t1
        )
    SELECT DISTINCT ON (1)
           x.t1
         , min(price)         OVER w
         , max(price)         OVER w
         , first_value(price) OVER w
         , last_value(price)  OVER w
    FROM   x
    JOIN   ticker y ON y.t >= x.t1  -- use LEFT JOIN to include empty intervals
                   AND y.t <  x.t2  -- don't use BETWEEN
    WINDOW w AS (PARTITION BY x.t1)
    ORDER  BY x.t1;
    

    Related answers with more explanation:

    • Best way to count records by arbitrary time intervals in Rails+Postgres
    • Select first row in each GROUP BY group?
    0 讨论(0)
提交回复
热议问题