2016-06-13 64 views
0

日期我還沒有發現類似的問題,但很樂意指出,以一個或回答...順序按日期,添加日期之前和PostgreSQL後子查詢

背景 我有一個數據庫:每月600萬行車輛的DB1。整個年份中有400k行的事件的DB2。兩者都包含位置(x,y)。我想通過postGIS中的日期和距離來交叉引用它們。理想情況下,我希望DB2中的每個事件都有一個距離DB1中的車輛距離的直方圖,這些距離在1小時之前和之後都有說法。但事前我躍躍欲試的DB1,因此我的問題

問題 我想在DB1 time_prevtime_nexttime_sequence添加對每輛車每天這裏

DB1 beforeDB1 after 鏈接清理數據從DB1塊:https://docs.google.com/spreadsheets/d/1_mz1JqQJu4VZ7iJ6WLezH7rZhurOIPDQu3flv8Qz058/edit?usp=sharing

我仍然不知道如何從那裏繼續這樣的想法將受到歡迎...

+1

閱讀關於'LEAD()/ LAG()'窗口函數。 – sagi

回答

1

使用window functions

select 
    *, 
    lag(timestamp) over wa time_prev, 
    lead(timestamp) over wa time_next, 
    to_char(timestamp, 'yyyymmdd') || to_char(row_number() over wd, 'fm0009') time_sequence 
from db1 
window 
    wa as (partition by vehicle_id order by objectid), 
    wd as (partition by vehicle_id, timestamp::date order by objectid); 


objectid | vehicle_id |  timestamp  |  time_prev  |  time_next  | time_sequence 
----------+------------+---------------------+---------------------+---------------------+--------------- 
     1 |   1 | 2009-06-01 11:57:43 |      | 2009-06-01 11:09:16 | 200906010001 
     4 |   1 | 2009-06-01 11:09:16 | 2009-06-01 11:57:43 | 2009-06-01 10:16:28 | 200906010002 
     6 |   1 | 2009-06-01 10:16:28 | 2009-06-01 11:09:16 | 2009-06-01 09:33:01 | 200906010003 
     11 |   1 | 2009-06-01 09:33:01 | 2009-06-01 10:16:28 | 2009-06-01 11:30:19 | 200906010004 
     12 |   1 | 2009-06-01 11:30:19 | 2009-06-01 09:33:01 |      | 200906010005 
     2 |   2 | 2009-06-01 10:42:19 |      | 2009-06-01 11:02:23 | 200906010001 
     3 |   2 | 2009-06-01 11:02:23 | 2009-06-01 10:42:19 | 2009-06-01 10:32:19 | 200906010002 
     7 |   2 | 2009-06-01 10:32:19 | 2009-06-01 11:02:23 | 2009-06-01 09:20:31 | 200906010003 
     9 |   2 | 2009-06-01 09:20:31 | 2009-06-01 10:32:19 | 2009-06-01 11:56:23 | 200906010004 
     13 |   2 | 2009-06-01 11:56:23 | 2009-06-01 09:20:31 |      | 200906010005 
     5 |   3 | 2009-06-01 11:56:47 |      | 2009-06-01 10:52:19 | 200906010001 
     8 |   3 | 2009-06-01 10:52:19 | 2009-06-01 11:56:47 | 2009-06-01 11:06:39 | 200906010002 
     10 |   3 | 2009-06-01 11:06:39 | 2009-06-01 10:52:19 |      | 200906010003 
(13 rows) 
+0

這工作,TNX)花了61分鐘約6百萬行。任何想法如何繼續? – Lizardie

+1

您可以通過定義索引'create index on db1(vehicle_id,objectid)'來加快查詢速度。我想你可以提出一個關於下一步的新問題(對我來說這不是很清楚)。 – klin