Steve
Steve

Reputation: 505

Divide by zero error encountered. T-SQL

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.

Upvotes: 2

Views: 2254

Answers (1)

Peter Radocchia
Peter Radocchia

Reputation: 11007

Here's a simple way to control for divide-by-zero errors, without repeating yourself, using NULLIF(...,0):

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)) 
   / NULLIF(datediff(ss, LAG(event_timestamp, 1) OVER (PARTITION BY machine_id ORDER BY event_timestamp), event_timestamp),0)
FROM Simple_speed

The expression will now return NULL for rows where the denominator is zero.

Upvotes: 1

Related Questions