使用子查询更新列,过滤掉空值

时间:2015-02-04 03:36:29

标签: sql sql-update

我尝试使用子查询更新列。但它给出了一个错误:

  

无法将PRODUCT.AVERAGE_COST更新为NULL

当子查询结果为null时,我不知道如何更新。

UPDATE PRODUCT P SET P.AVERAGE_COST = 
    (SELECT 
        SUM(C.COST)/SUM(C.QTY)
    FROM PRODUCT_COSTS C
    WHERE C.PRODUCT_CODE = P.PRODUCT_CODE 
    GROUP BY C.PRODUCT_CODE )

如果SUM(C.QTY)0或子查询结果为null,我根本不想更新。
查询应该在Oracle,MySQL,MSSQL,PostgreSQL上运行。

2 个答案:

答案 0 :(得分:0)

如果你使用的是MSSQL,请试试这个:

UPDATE PRODUCT P SET P.AVERAGE_COST = 
(SELECT 
    CASE WHEN ISNULL(SUM(C.QTY),0)='0' THEN '0' ELSE ISNULL(SUM(C.COST),0)/ISNULL(SUM(C.QTY),0) END
FROM PRODUCT_COSTS C
WHERE C.PRODUCT_CODE = P.PRODUCT_CODE 
GROUP BY C.PRODUCT_CODE )

答案 1 :(得分:0)

您应该在查询中添加WHERE子句。所以看起来应该是这样的:

UPDATE PRODUCT P SET P.AVERAGE_COST = 
    (SELECT SUM(C.COST)/SUM(C.QTY)
     FROM PRODUCT_COSTS C
     WHERE C.PRODUCT_CODE = P.PRODUCT_CODE)
WHERE
    (SELECT COUNT(1)
     FROM PRODUCT_COSTS C
     WHERE C.PRODUCT_CODE = P.PRODUCT_CODE ) > 0
AND
    (SELECT SUM(C.QTY)
     FROM PRODUCT_COSTS C
     WHERE C.PRODUCT_CODE = P.PRODUCT_CODE ) <> 0

您可以在SQLFiddle

中查看