[英]How to avoid DIVIDE BY ZERO error in an SQL query
SELECT YEAR, period, round((1- sum(rej_qty) / sum(recd_qty))*100, 0)
FROM TAB_A
WHERE sid = '200'
AND sdid IN ('4750')
AND
(
(
YEAR ='2011'
AND period IN('01_JAN')
)
OR
(
YEAR = '2010'
AND period IN('02_FEB','03_MAR','04_APR','05_MAY','06_JUN','07_JUL','08_AUG','09_SEP','10_OCT','11_NOV','12_DEC')
)
)
group by year, period
For a particular month, recd_qty is ZERO because of which I am getting DIVIDE BY ZERO error. 对于特定月份,recd_qty为零,因为我得到了DIVIDE BY ZERO错误。
Is there any way to avoid DIVIDE BY ZERO error? 有什么方法可以避免DIVIDE BY ZERO错误吗?
I there any way where in that particular month is ignored? 我有什么方法可以忽略那个特定的月份?
Have you tried using NULLIF()
? 你尝试过使用NULLIF()
吗?
SELECT
( 100 / NULLIF( 0, 0 ) ) AS value
;
Oracle Doc Oracle Doc
http://www.oracle-base.com/articles/9i/ANSIISOSQLSupport.php#NULLIFFunction http://www.oracle-base.com/articles/9i/ANSIISOSQLSupport.php#NULLIFFunction
Another example 另一个例子
http://www.bennadel.com/blog/984-Using-NULLIF-To-Prevent-Divide-By-Zero-Errors-In-SQL.htm http://www.bennadel.com/blog/984-Using-NULLIF-To-Prevent-Divide-By-Zero-Errors-In-SQL.htm
If you want to ignore such records you can use a subquery 如果要忽略此类记录,可以使用子查询
SELECT YEAR, period, round((1- rej_sum / recd_sum)*100, 0) FROM
(
SELECT YEAR, sum(rej_qty) rej_sum, sum(recd_qty) recd_sum
FROM TAB_A
WHERE sid = '200'
AND sdid IN ('4750')
AND
(
(
YEAR ='2011'
AND period IN('01_JAN')
)
OR
(
YEAR = '2010'
AND period IN ('02_FEB','03_MAR','04_APR','05_MAY','06_JUN','07_JUL','08_AUG','09_SEP','10_OCT','11_NOV','12_DEC')
)
)
group by year, period
)
WHERE recd_sum <> 0;
If you want to keep them and handle the division by zero issue, you can use decode or case 如果你想保留它们并通过零问题处理除法,你可以使用解码或大小写
SELECT YEAR, period, DECODE(recd_qty, 0, NULL, round((1- sum(rej_qty) / sum(recd_qty))*100, 0))
round(ISNULL(
((1- sum(rej_qty)) / NULLIF( (sum(recd_qty))*100), 0 )),
0
),0)
If you replace your division using NULLIF to set a NULL when there is divide by zero, then an ISNULL to replace the NULL with a 0 - or indeed whatever value you want it to. 如果使用NULLIF替换除法以在除以零时设置NULL,则使用ISNULL将NULL替换为0 - 或者实际上是您想要的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.