使用子查询更新列,过滤掉空值
Update column with subquery, filter out null values
我正在尝试使用子查询更新列。但它给出了一个错误:
cannot update PRODUCT.AVERAGE_COST to 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 上 运行。
如果您使用的是 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 )
您应该在查询中添加 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
中查看
我正在尝试使用子查询更新列。但它给出了一个错误:
cannot update PRODUCT.AVERAGE_COST to 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 上 运行。
如果您使用的是 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 )
您应该在查询中添加 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
中查看