How can I change NULL to 0 when getting a single value from a SQL function?

前端 未结 8 1010
刺人心
刺人心 2021-02-06 20:02

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 (DateAdd         


        
8条回答
  •  广开言路
    2021-02-06 20:41

    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.

提交回复
热议问题