2017-01-25 71 views
0

PostgreSQL的時間我使用postgres的(RDS),用於存儲時間序列數據序列區間

比方說,我的數據是這樣的:

  • 時間戳:(索引和分區鍵)
  • 來源:整數索引
  • 數據:二進制JSON包含的數據
timestamp   | source | data 
---------------------+----------+------------------ 
2017-01-24 19:24:41 | 1  | { some jsonb } 
2017-01-24 19:25:41 | 1  | { some jsonb } 
2017-01-24 19:25:41 | 2  | { some jsonb } 
2017-01-24 19:26:41 | 3  | { some jsonb } 
2017-01-24 19:32:41 | 1  | { some jsonb } 
2017-01-24 19:33:41 | 2  | { some jsonb } 
2017-01-24 19:45:41 | 3  | { some jsonb } 
2017-01-24 19:50:41 | 1  | { some jsonb } 
2017-01-24 19:56:41 | 1  | { some jsonb } 
2017-01-24 20:01:41 | 1  | { some jsonb } 

我想該數據由source和排序有由間隔意義分割數據比方說,通過15分鐘車間隔分開。 我還要分裂它區間時喜歡round的時間。

到目前爲止我

SELECT date_trunc('hour', timestamp) + date_part('minute', timestamp)::int/15 * interval '15 min' AS fifteen_minutes, data 
FROM MY_TABLE 
where source=1 
GROUP BY data, fifteen_minutes 
ORDER BY fifteen_minutes desc 

它返回

fifteen_minutes  | source | data 
---------------------+----------+------------------ 
2017-01-24 19:15:00 | 1  | { some jsonb } 
2017-01-24 19:15:00 | 1  | { some jsonb } 
2017-01-24 19:30:00 | 1  | { some jsonb } 
2017-01-24 19:45:00 | 1  | { some jsonb } 
2017-01-24 19:45:00 | 1  | { some jsonb } 
2017-01-24 20:00:00 | 1  | { some jsonb } 

的問題是,我仍然得到每個間隔多個結果。我想通過間隔distinct並獲得最接近時間戳

理想我想獲得:(每間隔一個結果)

fifteen_minutes  | source | data 
---------------------+----------+------------------ 
2017-01-24 19:15:00 | 1  | { some jsonb } 
2017-01-24 19:30:00 | 1  | { some jsonb } 
2017-01-24 19:45:00 | 1  | { some jsonb } 
2017-01-24 20:00:00 | 1  | { some jsonb } 

任何更好的主意嗎? 謝謝!

+1

請根據上述數據發佈預期的輸出 – GurV

+2

對於一個源和任何15分鐘的桶,您將如何決定使用哪個「數據」值? –

+0

從'2017-01-24 19:24:41'或'2017-01-24 19:25:41' =>'19:24:41'的「 」的「最接近」值最接近19: 15。 目前碼通過地圖處理這個邏輯減少的結果 –

回答

1
select distinct on (fifteen_minutes, source) 
    fifteen_minutes, source, data 
from (
    select 
     to_timestamp((extract(epoch from timestamp)/(15 * 60))::int * 15 * 60) as fifteen_minutes, 
     data, timestamp 
    from t 
) t 
order by 
    fifteen_minutes, source, 
    abs(extract(epoch from timestamp) - extract(epoch from fifteen_minutes)) 
+0

感謝!!!! Clodo阿爾內託! –