使用聚合值更新字段

时间:2017-09-30 05:33:24

标签: sql-server

我正在尝试根据多个子表记录更新父表的所有行 我收到以下错误

  

聚合可能不会出现在UPDATE语句的集合列表中

UPDATE p
SET p.QuantityOnHand =
    (ISNULL(SUM(ISNULL(b.Qty, 0)), 0) -
     ISNULL(SUM(ISNULL(i.Qty, 0)), 0) -
     ISNULL(SUM(ISNULL(s.Qty, 0)), 0))
FROM Products p

INNER JOIN BillDetails b ON p.ProductId = b.Pid
INNER JOIN InvoiceDetails i ON p.ProductId = i.Pid
INNER JOIN SalesDetails s ON p.ProductId = s.Pid

1 个答案:

答案 0 :(得分:0)

你错过了一个小组,但这仍然无效。 我的解决方案是首先创建一个临时表来存储结果,然后使用临时表进行更新:

SELECT p.Pid, (ISNULL(SUM(ISNULL(b.Qty, 0)), 0) -
 ISNULL(SUM(ISNULL(i.Qty, 0)), 0) -
 ISNULL(SUM(ISNULL(s.Qty, 0)), 0)) AS Result
INTO #tmp
FROM Products p
INNER JOIN BillDetails b ON p.ProductId = b.Pid
INNER JOIN InvoiceDetails i ON p.ProductId = i.Pid
INNER JOIN SalesDetails s ON p.ProductId = s.Pid
GROUP BY p.Pid


 UPDATE p
    SET p.QuantityOnHand = t.Result
   FROM Products p
  INNER JOIN #tmp t ON t.Pid = p.Pid