Gunakan fungsi jendela .
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)