避免除以0错误

时间:2013-11-13 15:13:19

标签: sql sql-server

我一直在尝试在SQL中进行计算,但我遇到的问题是,有时候其中一个数字可能为0,这当然会导致SQL Server错误。我试图将我的case语句从null修改为0,但这样做会导致为其他项返回错误数据。在这种情况下我应该做些什么来准确地返回计算,如果它会返回除以0的错误,返回0?

Select product,
count(distinct case when numavaliable is null then ID else null end),
count(distinct product),
count(distinct case when numavaliable is null then ID else null end)/count(distinct      product)
From ProductionInfo
Group By product

2 个答案:

答案 0 :(得分:4)

使用NULLIFISNULL功能。

Select product,
count(distinct case when numavaliable is null then ID else null end),
count(distinct product),
ISNULL (count(distinct case when numavaliable is null then ID else null end)/NULLIF(count(distinct      product), 0), 0)
From ProductionInfo
Group By product

答案 1 :(得分:-2)

您可以在列上使用IF来检查它是否为0.

SELECT IF(y = 0, 'NaN', x/y) FROM YOURTABLE;