按日期排序,使用子查询在postgresql之后添加日期和日期

时间:2016-06-13 10:11:01

标签: postgresql timestamp

我没有找到类似的问题,但很高兴被指出一个或回答......

背景 我有一个数据库:每个月有6百万行的车辆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 个答案:

答案 0 :(得分: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)