10
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

对于特定月份,recd_qty 为零,因此我收到除以零错误。

有什么办法可以避免除零错误?

我有什么办法在那个特定月份被忽略?

4

4 回答 4

23

你试过使用NULLIF()吗?

 SELECT
 ( 100 / NULLIF( 0, 0 ) ) AS value
 ;

Oracle 文档
http://www.oracle-base.com/articles/9i/ANSIISOSQLSupport.php#NULLIFFunction

另一个例子
http://www.bennadel.com/blog/984-Using-NULLIF-To-Prevent-Divide-By-Zero-Errors-In-SQL.htm

于 2011-02-17T10:45:05.153 回答
9

如果您想忽略此类记录,您可以使用子查询

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;

如果您想保留它们并处理除以零的问题,您可以使用 decode 或 case

SELECT  YEAR, period, DECODE(recd_qty, 0, NULL, round((1- sum(rej_qty) / sum(recd_qty))*100, 0)) 
于 2011-02-17T10:42:36.013 回答
4
round(ISNULL(
((1- sum(rej_qty)) / NULLIF( (sum(recd_qty))*100), 0 )),
0
),0)

如果您在除以零时使用 NULLIF 替换除法以设置 NULL,然后使用 ISNULL 将 NULL 替换为 0 - 或者实际上是您想要的任何值。

于 2011-02-17T10:49:28.197 回答
0

CASE WHEN sum(recd_qty) <> 0 THEN round((1- sum(rej_qty) / sum(recd_qty))*100, 0) ELSE 0 END

于 2019-10-17T14:37:26.700 回答