How can I change NULL to 0 when getting a single v

2019-03-17 02:20发布

I have a query that counts the price of all items between two dates. Here is the select statement:

SELECT SUM(Price) AS TotalPrice 
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

You can assume all of the tables have been set up properly.

If I do a select between two dates and there are no items within that date range, the function returns NULL as the TotalPrice rather than 0.

How can I make sure that if no records are found, 0 gets returned rather than NULL?

标签: sql tsql null sum
8条回答
Deceive 欺骗
2楼-- · 2019-03-17 03:07
SELECT 0+COALESCE(SUM(Price),0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)
查看更多
走好不送
3楼-- · 2019-03-17 03:11

Most database servers have a COALESCE function, which will return the first argument that is non-null, so the following should do what you want:

SELECT COALESCE(SUM(Price),0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

[edit]

Just to clarify things since there seems to be a lot of discussion about "COALESCE/ISNULL will still return NULL if no rows match", try this query you can copy-and-paste into SQL Server directly as-is:

SELECT coalesce(SUM(column_id),0) AS TotalPrice 
FROM sys.columns
WHERE (object_id BETWEEN -1 AND -2)

Note that the where clause excludes all the rows from sys.columns from consideration, but the 'sum' operator still results in a single row being returned that is null, which coalesce fixes to be a single row with a 0.

I hope this helps explain it.

查看更多
登录 后发表回答