2012-07-18 91 views
2

聚集這是查詢我到目前爲止,創建每日酒吧:檢索任意時間間隔

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)); 

更改「小時」到「分」或「天」會給我對應於這些酒吧單位。

但是,如果我想要5分鐘或15分鐘的酒吧呢? date_trunc()不支持這些,我正在尋找一個很好的方法來做到這一點。

回答

5

對於15分鐘的間隔,建立在你的例子:

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)); 

工程5分鐘了。


任何規律的時間間隔更通用的解決方案,跨越任何時間段:

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; 

相關答案與更多的解釋:

+0

嗨'x'和'y'是什麼意思? – newBike 2014-12-10 09:43:41

+0

@poc:'x'是[** CTE **]的名稱(http://www.postgresql.org/docs/current/interactive/queries-with.html),'y'是一個表別名對'ticker',這裏聲明:'JOIN ticker y',這是'JOIN ticker AS y'的縮寫 – 2014-12-10 10:17:34