SQL Server:使用聚合进行更新

时间:2013-09-04 17:27:27

标签: sql sql-server tsql

我已经在存储过程中编写了以下代码,但它没有按预期方式工作

UPDATE  dbo.products
SET     stock = t.totalquantity
FROM    dbo.products
    INNER JOIN ( SELECT accountdetail.itemnumber ,
                        SUM(accountdetail.quantity + products.stock) totalquantity
                 FROM   accountdetail ,
                        products
                 WHERE  accountdetail.orderid = @accountorderid
                        AND dbo.products.itemnumber = accountdetail.itemnumber
                 GROUP BY accountdetail.itemnumber
               ) t ON dbo.products.itemnumber = t.itemnumber

如果只有1个带有数量的项目编号,但是如果有2个相同的项目编号,则数量结果最终不正确,则代码正常工作

例如

  • products.stock = 4
  • accountdetail.duantity = 2来自一个项目编号

  • products.stock = 6 - 这是正确的

  • products.stock = 4

  • accountdetail.duantity = 2来自两个相同的项目编号

  • products.stock = 12 - 这是不正确的,我需要帮助来理解出了什么问题。

提前谢谢。

2 个答案:

答案 0 :(得分:1)

这应该解决它。

取出()

中的产品

你是否在()

之外加入
UPDATE dbo.products
SET    stock = t.totalquantity + stock
FROM   dbo.products
    INNER JOIN ( SELECT accountdetail.itemnumber ,
                        SUM(accountdetail.quantity) totalquantity
                 FROM   accountdetail
                 WHERE  accountdetail.orderid = @accountorderid
                 GROUP BY accountdetail.itemnumber
               ) t ON dbo.products.itemnumber = t.itemnumber

答案 1 :(得分:0)

尝试此查询

with cte as (
   select a.itemnumber, sum(a.quantity) as totalquantity
   from accountdetail as a
   where a.orderid = @accountorderid
   group by a.itemnumber
)
update dbo.products set
    stock = stock + t.totalquantity
from dbo.products as p
    inner join cte as t on c.itemnumber = p.itemnumber