關於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
相關文章
相關標籤/搜索