关于SQL语句中SUM函数返回NULL的解决办法

SUM 是SQL语句中的标准求和函数,若是没有符合条件的记录,那么SUM函数会返回NULL。sql

但多数状况下,咱们但愿若是没有符合条件记录的状况下,咱们但愿它返回0,而不是NULL,那么咱们能够使用例以下面的方法来处理:函数

SELECT COALESCE(SUM(name),0) FROM person WHERE id > 0this

 

行了,这下就不用费事去处理返回结果是否为NULL的状况了。code

COALESCE 函数的意思是返回参数列表中第一个为空的值,该方法容许传入多个参数,该函数也是SQL中的标准函数。blog

而后查了查关于对于NULL值的判断。地址:http://www.w3schools.com/sql/sql_isnull.aspget

SQL Server / MS Accessit

 

1 SELECT ProductName,UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0)) 2  FROM Products

 

Oracleio

Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve the same result:function

1 SELECT ProductName,UnitPrice*(UnitsInStock+NVL(UnitsOnOrder, 0)) 2  FROM Products

MySQLclass

MySQL does have an ISNULL() function. However, it works a little bit different from Microsoft's ISNULL() function.

In MySQL we can use the IFNULL() function, like this:

1 SELECT ProductName,UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder, 0)) 2  FROM Products

or we can use the COALESCE() function, like this:

 

1 SELECT ProductName,UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0)) 2  FROM Products
相关文章
相关标签/搜索