我有以下在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
然而,正如错误所示,我有一个除以零的问题。
在这个问题上有很多帖子和答案,但我很难接受工作。
答案 0 :(得分: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
。