当前位置:网站首页>Demonstration of the processing of divisor 0 in SQL

Demonstration of the processing of divisor 0 in SQL

2022-06-24 04:04:00 User 8989785

When we make statistics , It is common to find the percentage , Chain ratio , Year on year and other situations that need to be divided by a certain number , And if the divisor is 0, The database will report errors . So how do we deal with this situation ? Let's use an example to explain the processing method .


Situation 1

for example

SELECT  A/B  FROM TAB

In this case , The general treatment is to use CASE WHEN To judge B Value

SELECT  
CASE WHEN B=0 THEN 0 ELSE A/B END   
FROM TAB 

So when B If it is 0, Let's just assign a value , avoid A/B Participate in the calculation and report errors .

Situation two

The above is a common situation , But what if you encounter the following aggregate function ?

for example

SELECT  SUM(A)/COUNT(B) FROM TAB

In this case CASE WHEN Can't judge COUNT(B) The value of the , because WHEN The following conditions cannot use aggregate functions ( Grammar requires ), At this time, we can deal with it like this

SELECT   
ISNULL(SUM(A)/NULLIF(COUNT(B),0),0)   
FROM  TAB 

Two functions are used here ,NULLIF() and ISNULL()

NULLIF Function has two arguments , The definition is as follows :

NULLIF( expression1 , expression2 )

Its function is : If two specified expressions are equal , Just go back to NULL value .

ISNULL The function also has two arguments , The definition is as follows :

ISNULL( expression1 , expression2 )

Its effect is : If the result of the first parameter is NULL, Just return the value of the second parameter .

When COUNT(B) As the result of the 0 when , Exactly the same as the second given parameter 0 equal , This is the time NULLIF The function will return NULL, and SUM(A) Divided by NULL The result is NULL, Outer use ISNULL Function realignment NULL Value for judgment , The end result is 0 了 .

These two methods are that we deal with the divisor as 0 The situation of the , Be sure to remember !

原网站

版权声明
本文为[User 8989785]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/09/20210913131307339C.html