I have the following T-SQL that I run in SQL 2012
SELECT machine_id, speed_gps_kph, odometer_total, event_timestamp,
1.0 * (speed_gps_kph - LAG(speed_gps_kph, 1) OVER (PARTITION BY machine_id ORDER BY event_timestamp)) /
datediff(ss, LAG(event_timestamp, 1) OVER (PARTITION BY machine_id ORDER BY event_timestamp), event_timestamp)
FROM Simple_speed
However, as the error indicates, I have an issue with dividing by zero.
There are quite a few posts and answers on this issue, but I am struggling to get then to work.
Here’s a simple way to control for divide-by-zero errors, without repeating yourself, using
NULLIF(...,0):The expression will now return
NULLfor rows where the denominator is zero.