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条回答
虎瘦雄心在
2楼-- · 2019-03-17 02:47

The easiest way to do this is just to add zero to your result.

i.e.

$A=($row['SUM'Price']+0);
echo $A;

hope this helps!!

查看更多
虎瘦雄心在
3楼-- · 2019-03-17 02:56

Edit: Looks like everyone else beat me to it haha

Found the answer.

ISNULL() determines what to do when you have a null value.

In this case my function returns a null value so I needed specify a 0 to be returned instead.

SELECT ISNULL(SUM(Price), 0) AS TotalPrice 
FROM Inventory
WHERE (DateAdded 
BETWEEN @StartDate AND @EndDate)
查看更多
姐就是有狂的资本
4楼-- · 2019-03-17 02:57
SELECT ISNULL(SUM(Price), 0) AS TotalPrice 
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

That should do the trick.

查看更多
我命由我不由天
5楼-- · 2019-03-17 03:01

You could use

SELECT ISNULL(SUM(ISNULL(Price, 0)), 0).

I'm 99% sure that will work.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-03-17 03:04
SELECT COALESCE(
    (SELECT SUM(Price) AS TotalPrice 
    FROM Inventory
    WHERE (DateAdded BETWEEN @StartDate AND @EndDate))
    , 0)

If the table has rows in the response it returns the SUM(Price). If the SUM is NULL or there are no rows it will return 0.

Putting COALESCE(SUM(Price), 0) does NOT work in MSSQL if no rows are found.

查看更多
再贱就再见
7楼-- · 2019-03-17 03:04

ORACLE/PLSQL:

NVL FUNCTION

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

This SQL statement would return 0 if the SUM(Price) returned a null value. Otherwise, it would return the SUM(Price) value.

查看更多
登录 后发表回答