如何将更新与 select 查询相关联

How to correlate update with select query

我想根据同一 table 中不同列中的值更新 table 库存项目中列 SalesDifference20132015 中的每一行。我知道 SELECT 查询有效,但是当我将它插入我的更新查询时,我得到子查询返回超过 1 个值的错误。我如何将我的 select 查询与我的更新相关联?

UPDATE warehouse.StockItems
    SET SalesDifference20132015 =
    (SELECT (SELECT COUNT(*)
    FROM Sales.Orders o
    join sales.OrderLines ol ON o.OrderID = ol.OrderID
    WHERE ol.StockItemID = si.StockItemID AND YEAR(o.OrderDate) = 2013
    Group by ol.StockItemID)
    -
    (SELECT COUNT(*)
    FROM Sales.Orders o
    join sales.OrderLines ol ON o.OrderID = ol.OrderID
    WHERE ol.StockItemID = si.StockItemID AND YEAR(o.OrderDate) = 2015
    Group by ol.StockItemID)

    FROM Warehouse.StockItems si
    )

像这样的东西应该可以工作:

UPDATE si
SET SalesDifference20132015 = DIFF.Diff
FROM
    warehouse.StockItems si
    JOIN
        (
            SELECT DISTINCT
                StockItemID
                ,
                    (
                        SELECT COUNT(*)
                        FROM
                            Sales.Orders o
                            JOIN sales.OrderLines ol ON o.OrderID = ol.OrderID
                        WHERE ol.StockItemID = si.StockItemID AND YEAR(o.OrderDate) = 2013
                        GROUP BY ol.StockItemID
                    )
                        -
                    (
                        SELECT COUNT(*)
                        FROM
                            Sales.Orders o
                            JOIN sales.OrderLines ol ON o.OrderID = ol.OrderID
                        WHERE ol.StockItemID = si.StockItemID AND YEAR(o.OrderDate) = 2015
                        GROUP BY ol.StockItemID
                    ) Diff
            FROM Warehouse.StockItems si
        ) DIFF
    ON si.StockItemID = DIFF.StockItemID