Skip to main content
4 of 8
added 224 characters in body

split point track based on time

With PostgreSQL 13.6 have a table of multiple GPS points already group by track_id (HEX number not sequential), and from where ST_Makeline is made to build a line.

Some of these tracks have a time gap between them bigger than a given value (say 10 minutes). Need to split the track_id where these gaps exits, to a track_id (before 1st gap) and track_id+1 (after 1st gap) ... track_id+n (after n_st gap).

the track_id is a non-sequential large intervals HEX number, so no issues on adding a few additional units (1 to 2 gaps per track) to it.

The actual location geom is irrelevant in the analysis, since the points in the gap can be close (time spent on same position) or far apart (loose of reception).

This is only to clean and organize data, before any further analysis.

table example:

track_id geom time
123 aaaa 10:01
123 aaab 10:02
123 aaac 10:05
123 aaad 10:45
123 aaae 10:47
123 aaaf 10:49
234 aaab 10:52
234 aaac 10:55
234 aaaa 10:58

to build, new column 'new_track_id`:

track_id geom time new_track_id
123 aaaa 10:01 123
123 aaab 10:02 123
123 aaac 10:05 123
123 aaad 10:45 124
123 aaae 10:47 124
123 aaaf 10:49 124
234 aaab 10:52 234
234 aaac 10:55 234
234 aaaa 10:58 234

create table public.testtime (id SERIAL primary key, track_id varchar, time1 time);

Test data:

insert into public.testtime (track_id, time1)
    values (123,    '10:01:00'),
           (123,    '10:02:00'),
           (123,    '10:05:00'),
           (123,    '10:45:00'),
           (123,    '10:47:00'),
           (123,    '10:49:00'),
           (234,    '10:52:00'),
           (234,    '10:55:00'),
           (234,    '10:58:00');

EDIT:

to calculate time difference between rows

SELECT *,
CASE 
   WHEN time-LAG(time) OVER (PARTITION BY track_id ORDER BY time) > '00:10' 
   THEN TRUE 
   END) AS chk_diff

to populate teh row after the true : but seems not working

SELECT *,
 MAX(chk_diff) FROM table t2
 WHERE t2.track_id=table.track_id AND
       t2.time>(CASE WHEN chk_diff=TRUE then table.time END)

to change the track_id (simplify for now, change the last digit to 'x' : is not more an HEX, and only allows for a gap) looking for better

REPLACE(track_id,RIGHT(track_id,1),'X') as new_track_id