将两个表值相加并在一列为空时显示值

时间:2018-01-17 12:06:35

标签: sql

我有两个表的列,我想要对两个值求和,但我的一列为空,当我在查询下运行时,它显示全部为空。

SELECT
    Product.ProductID, 
    Product.ProductName, 
    (select round(sum(quantity),18, 2)from [ProductPur] where [ProductPur].[ProductID] = product.ProductID) AS Purchased_quantity,
    (select round(sum(quantity),18 ,2)from [PGDN] where [PGDN].[ProductID] = product.ProductID)+(select round(sum(quantity),18 ,2)from [returnnonreturndetails] where [returnnonreturndetails].[ProductID] = product.ProductID) AS Sold_quantity,
     (select round(sum(quantity),18 ,2)from [ProductPur] where [ProductPur].[ProductID] = product.ProductID) - (select round(sum(quantity),18, 2)from [PGDN] where [PGDN].[ProductID] = product.ProductID) AS Stock
FROM Product
ORDER BY Product.ProductName; 

3 个答案:

答案 0 :(得分:1)

您需要使用isnull函数检查值,即isnull(quantity,0)

答案 1 :(得分:1)

通用SQL解决方案使用COALESCE()

SELECT p.ProductID, p.ProductName, 
       (select round(sum(quantity),18, 2) from ProductPur pp where pp.[ProductID] = p.ProductID) AS Purchased_quantity,
       (COALESCE( (select round(sum(quantity), 18, 2) from [PGDN] pg where pg.[ProductID] = p.ProductID), 0) +
        COALESCE( (select round(sum(quantity), 18, 2) from returnnonreturndetails rd where rd.[ProductID] = p.ProductID), 0)
       ) AS Sold_quantity,
       (COALESCE( (select round(sum(quantity), 18, 2) from ProductPur pp where pp.[ProductID] = p.ProductID), 0) -
        COALESCE( (select round(sum(quantity), 18, 2) from [PGDN] pg where pg.[ProductID] = p.ProductID), 0)
       ) AS Stock
FROM Product p
ORDER BY p.ProductName; 

在SQL Server中,出于性能原因,ISNULL()是更好的选择。

答案 2 :(得分:0)

根据您的DBMS,您必须使用IFNULL()(MySQL),ISNULL()(SQL Server,MS Access)或NVL()(Oracle)。您也可以使用COALESCE(),这将是通用解决方案。

所有这些功能都使用相同:

ISNULL($statement,$value_if_statement_is_null)

例如

select round(sum(isnull(quantity,0)),18, 2)
from [ProductPur]
where [ProductPur].[ProductID] = product.ProductID)