2

I want to calculate speed at every point for each device_id, such that there is a new column of "speed" is attached to the current dataset

My dataset is like

imei(device_id)         point_geom(SRID 4326)           time_created

Here is my code so far:

select st_distance((points_geom::geography),lag(points_geom::geography) over (partition by imei order by time_created))
 / (time_created - lag(time_created) over(partition by imei order by time_created))  as speed
from dataset 

I am receiving this error:

SQL Error [42883]: ERROR: operator does not exist: double precision / interval

1 Answer 1

2

Arithmetic on two TIMESTAMP types return an INTERVAL type - use their EPOCH second representations instead:

( EXTRACT(EPOCH FROM time_created) - EXTRACT(EPOCH FROM LAG(time_created) OVER(PARTITION BY imei ORDER BY time_created))) )::FLOAT8

Note:

You can EXTRACT(EPOCH FROM <INTERVAL>) directly, however the internal INTERVAL transformation function may introduce integer rounding inaccuracies.

3
  • thanks, I fixed that. Is my logic / way of calculating speed okay? or should I first make separate columns for lagged time, and lagged point_geom, then do the final calculation on these columns?
    – analyst92
    Commented Sep 29, 2022 at 9:34
  • also regarding the code you posted, does it give time difference in seconds? thanks
    – analyst92
    Commented Sep 29, 2022 at 9:41
  • 1
    Looks good to me, as a simplified speed approximation. As long as execution speed is good enough, don't clutter you base tables with pure utility columns. And yes, the difference will be (decimal) seconds.
    – geozelot
    Commented Sep 29, 2022 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.