Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

sql - Retrieve aggregates for arbitrary time intervals

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(price) OVER w,
last_value(price) OVER w
FROM ticker
WINDOW w AS (PARTITION BY date_trunc('hour',t));

Changing 'hour' to 'min' or 'day' would give me the bars corresponding to these units.

However, what if I want 5 min or 15 min bars? date_trunc() doesn't support these and I'm looking for a nice elegant way to do it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...