除以零错误sql

时间:2015-05-20 17:05:03

标签: mysql sql zero divide

我使用这个得到零除错误:

Select Top 100 *, Case (a.value)
    When 0.0
    Then Null
    Else ((cast(b.value as decimal) - cast(a.value as decimal))/cast(a.value as decimal)) * 100
    End
    as 'Montly Price Change (%)'
From AllProducts a
Join AllProducts b
On a.series_id=b.series_id And (b.Date = DATEADD(month, 1, a.Date))

我找不到办法解决它..我已经尝试了

Select Top 100 *, Case cast((a.value) as decimal)
    When 0.0
    Then Null
    Else ((cast(b.value as decimal) - cast(a.value as decimal))/cast(a.value as decimal)) * 100
    End
    as 'Montly Price Change (%)'
From AllProducts a
Join AllProducts b
On a.series_id=b.series_id And (b.Date = DATEADD(month, 1, a.Date))

但是由于某种原因,这会使我的整个列为空。

4 个答案:

答案 0 :(得分:0)

任何除以NULL的数字都会给出NULL,并且不会生成错误。

Select Top 100 *, Case cast((a.value) as decimal)
        When 0.0
        Then Null
        Else ((cast(b.value as decimal) - cast(a.value as decimal))/NULLIF(cast(a.value as decimal)),0) * 100
        End
        as 'Montly Price Change (%)'
    From AllProducts a
    Join AllProducts b
    On a.series_id=b.series_id And (b.Date = DATEADD(month, 1, a.Date))

如果您想返回零

COALESCE(cast(a.value as decimal))/NULLIF(cast(a.value as decimal)),0),0)

答案 1 :(得分:0)

使用NULLIF将起作用

Select Top 100 *,
    ((cast(b.value as decimal) - cast(a.value as decimal))/NULLIF(cast(a.value as decimal),0)) * 100

    as 'Montly Price Change (%)'
From AllProducts a
Join AllProducts b
On a.series_id=b.series_id And (b.Date = DATEADD(month, 1, a.Date))

答案 2 :(得分:0)

默认比例 - 小数点后的位数 - 对于"十进制"我认为,类型是0.结果,表达式中的分母值为< 1始终评估为0.尝试使用小数(10,3)。

答案 3 :(得分:0)

我猜你的价值都低于1?小数位数的默认值为0.因此,如果您的值小于1,则它们将全部转换为0.您可以使用cast(a.value as decimal(<precision>,<scale>))定义精度和比例,或者可以转换为浮点数。

这样的事情应该有效:

Select Top 100 *,
    (cast(b.value as float) - cast(a.value as float))/cast(nullif(a.value,0) as float)) * 100 as 'Montly Price Change (%)'
From AllProducts a
Join AllProducts b
On a.series_id=b.series_id And (b.Date = DATEADD(month, 1, a.Date))