sql-server - 有没有办法使用内连接更新 TOP (N),其中 N 是此类内连接的字段?

标签 sql-server sql-update

我正在尝试创建一个同步销售表和库存表的脚本。为此,我在库存表(每个库存项目有 1 条记录)上编写了更新,如下所示:

UPDATE TOP (q.QuantitySold) i
SET i.Converted = 1,
    i.CartID = q.CartID,
    i.ReservedDate = GETDATE()
FROM Inventory i
INNER JOIN
(
    SELECT product.ProductID, sales.CartID, COUNT(sales.ID) AS QuantitySold
    FROM Products product
    INNER JOIN Sales sales ON sales.ProductID = product.ProductID
    WHERE <conditions> 
    GROUP BY product.ProductID, sales.CartID
) q ON q.ProductID = i.ProductID
WHERE i.Converted = 0 AND i.CartID IS NULL 

但它不起作用,错误提示 q.QuantitySold 无法绑定(bind)。

有没有办法在不使用游标的情况下更新N条库存记录(等于销售数量)?我拒绝就这样放弃。

注意:这是实际查询的简化版本。

最佳答案

您可以使用ROW_NUMBER来枚举需要更新的库存项目。

WITH cteProducts AS(
    SELECT product.ProductID, sales.CartID, COUNT(sales.ID) AS QuantitySold
    FROM Products product
    INNER JOIN Sales sales ON sales.ProductID = product.ProductID
    WHERE <conditions> 
    GROUP BY product.ProductID, sales.CartID
),
cteInventory AS(
    SELECT *,
        ROW_NUMBER() OVER( PARTITION BY ProductID ORDER BY (SELECT NULL)) AS rn /*Change the ORDER BY for an actual column if needed, probably for FIFO*/
    FROM Inventory
    WHERE i.Converted = 0 
    AND i.CartID IS NULL 
)
UPDATE i
SET i.Converted = 1,
    i.CartID = q.CartID,
    i.ReservedDate = GETDATE()
FROM cteInventory i
INNER JOIN cteProducts q ON q.ProductID = i.ProductID
WHERE i.rn <= q.QuantitySold;

关于sql-server - 有没有办法使用内连接更新 TOP (N),其中 N 是此类内连接的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54599430/

相关文章:

c++ - 更新与特定行号相关的每一列的值? sqlite sqlite3

mysql - 无法处理带有特殊字符的代码

sql - 将一个表中的值更新到另一个表中

mysql - 更新语句中不存在需要更多时间

c# - 必须使用哪些命名空间才能使用 ADO.NET 连接到 SQL Server?

mysql - SQL - 最佳方式[期初期末余额]

sql - 如何在 SQL 中查找去年的同一个工作日?

sql-server - 如何更改 SQL Server 2005 中的默认事务隔离级别?

c# - 我可以使用 Entity Framework 在单个数据库调用中轻松评估多个 IQueryables 吗?

sql - 我的带有 JOIN 的 UPDATE 的 SQL 语法有什么问题?