2

我有以下在 SQL 2012 中运行的 T-SQL

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

但是,正如错误所示,我遇到了除以零的问题。

关于这个问题有很多帖子和答案,但我很难开始工作。

4

1 回答 1

1

这是一种控制被零除错误的简单方法,无需重复自己,使用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

该表达式现在将返回NULL分母为零的行。

于 2012-12-10T00:38:07.627 回答