I have a question that I’m sure you experts can easily answer 🙂
from a table in postgresql/postgis with the following content
ID | car | timestamp | geom | startflag
903 | test1 | 03.11.23 08:38:52 | 0101000020E61000001D33F55 | 4
904 | test1 | 03.11.23 08:39:02 | 0101000020E6100000A40117B | 0
905 | test1 | 03.11.23 08:39:13 | 0101000020E6100000740179C | 0
906 | test1 | 03.11.23 08:39:23 | 0101000020E6100000E68013C | 0
907 | test1 | 03.11.23 08:39:34 | 0101000020E610000014B1886 | 0
908 | test1 | 03.11.23 08:39:44 | 0101000020E61000004309E9D | 4
909 | test1 | 03.11.23 08:39:54 | 0101000020E61000004C6B781 | 0
910 | test1 | 03.11.23 08:40:05 | 0101000020E61000002DC6658 | 0
911 | test1 | 03.11.23 08:40:15 | 0101000020E6100000A0B591A | 0
912 | test1 | 03.11.23 08:40:26 | 0101000020E61000000E1A55E | 0
913 | test1 | 03.11.23 08:40:36 | 0101000020E6100000D7DF128 | 0
914 | test1 | 03.11.23 08:40:46 | 0101000020E61000001C1E673 | 4
915 | test1 | 03.11.23 08:40:57 | 0101000020E6100000DD24068 | 0
916 | test1 | 03.11.23 08:41:07 | 0101000020E6100000CBE48A4 | 0
917 | test1 | 03.11.23 08:41:17 | 0101000020E610000093FFC9D | 0
918 | test1 | 03.11.23 08:41:28 | 0101000020E61000000B3A6B0 | 0
I need all records with startflag=0 after (and with) startflag = 4 row as a path (Postgis Linestring over geom) order by timestamp, until and without next startflag=4
From next startflag=4 then next path and so on…
I tried lead and partitioning but I don’t know much about it
2
Answers
As always, there are several possible means to obtain what you want. The following SQL-statement is only one of them:
Some remarks:
As said: there are more ways to achieve the same result. This one can be a bit of a puzzle, but it works:
Some explanation:
Why does it work?
Let’s say we started with the following records (abbreviated column list):
Obviously there are 2 tracks for car ‘test1’, starting at tcid 1 and 4, so the first part of CTE "tracks" would result in the following table (where column "track" is filled with a new number sequence, starting with 1):
The second part would (temporarily) contain the following values:
In this result list, the newly created row_numbers again form a series of consecutive numbers, but the original tcid’s now have ‘holes’ in their sequence (some records were filtered away, when they had a startflag = 4).
One caveat: if the first inserted record in the original table was (for whatever reason) not flagged as a starting point, this query will create a linestring (given enough points for that track) but will assign a track number 0. That could quite easily be eliminated in the main query, using
WHERE track > 0
.