Subquery returned more than 1 value in update doesnt work

时间:2018-02-03 08:46:20

标签: sql-server sql-server-2008

I'm trying to update a SQL Server table with a sum of quantity for each item from another table.

Here is my first attempt:

UPDATE InventoryMaster
SET TemporaryStock = ((SELECT coalesce(SUM(Quantity), 0) AS Total
                       FROM InventoryTransTemp
                       WHERE CustomerID = '0'
                       GROUP BY InventoryItemID) -
                      (SELECT COALESCE(SUM(Quantity), 0) AS Total
                       FROM InventoryTransTemp
                       WHERE CustomerID > 0
                       GROUP BY InventoryItemID))

Here is my second example using join

UPDATE a 
SET a.TemporaryStock =((SELECT COALESCE(SUM(Quantity), 0) AS Total 
                        FROM InventoryTransTemp 
                        WHERE CustomerID = '0' 
                        GROUP BY InventoryItemID) - 
                       (SELECT COALESCE(SUM(Quantity), 0) AS Total 
                        FROM InventoryTransTemp  
                        WHERE CustomerID > 0 
                        GROUP BY InventoryItemID)) 
FROM InventoryMaster a 
INNER JOIN InventoryTransTemp b on a.InventoryItemID = b.InventoryItemID 

In both cases I get the same error

1 个答案:

答案 0 :(得分:1)

I think this is what you are intending to do here. The purpose of the subquery is to calculate temporary stock amounts, for each inventory item. We can move your subquery into a CTE, and then update join the master table.

WITH cte AS (
    SELECT
        InventoryItemID,
        COALESCE(SUM(CASE WHEN CustomerID = 0 THEN Quantity ELSE 0 END) -
                 SUM(CASE WHEN CustomerID > 0 THEN Quantity ELSE 0 END), 0) AS Total
    FROM InventoryTransTemp
    GROUP BY InventoryItemID
)

UPDATE a
SET TemporaryStock = b.Total
FROM InventoryMaster a
INNER JOIN cte b
    ON a.InventoryItemID = b.InventoryItemID;

Note that it is not clear what the name of the inventory ID join column is in the master table. I assumed it has the same name as in the temp table.