订购列时PostgreSQL除以零

时间:2014-03-04 12:08:13

标签: sql postgresql

SELECT wavelength, 
           (LEAD(wavelength) OVER (ORDER BY wavelength) - wavelength)/
           (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) 
           AS reflectance
    FROM  grassland1 

它在Postgresql中显示如下错误

ERROR:  division by zero
********** Error **********

ERROR: division by zero
SQL state: 22012

我将如何纠正这个人有人建议我

3 个答案:

答案 0 :(得分:2)

使用case然后

SELECT wavelength,
case when (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance)=0 
     then 0
     else ((LEAD(wavelength) OVER (ORDER BY wavelength) - wavelength)/
          (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance))
end reflectance
FROM  grassland1 

答案 1 :(得分:1)

试试这个:

SELECT wavelength, 
       (LEAD(wavelength) OVER (ORDER BY wavelength) - wavelength)/
       (CASE WHEN (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) = O THEN 1
        ELSE (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) END)
       AS reflectance
FROM  grassland1 

答案 2 :(得分:0)

这取决于当分母表达式(LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance)的计算结果为0时,您希望如何处理这种情况。假设您希望在计算结果为0时除以1,则可以执行以下操作:

SELECT wavelength, 
           (LEAD(wavelength) OVER (ORDER BY wavelength) - wavelength)/
           (CASE WHEN (LEAD(reflectance) OVER (ORDER BY wavelength) - reflectance) = 0 THEN 1 ELSE (LEAD(reflectance) OVER (ORDER BY wavelength) END)
           AS reflectance
    FROM  grassland1