根据聚合函数“SUM”更新选择:

时间:2011-09-09 05:41:51

标签: sql sql-server sql-server-2005 select sql-update

我有3张表格如下:

PODetail:

      PODetailID       POID     ItemID      POQuantity        StatusID
     ------------     ------   --------    ------------      ----------
          1             1         10          8.00              2
          2             1         17          33.00             2
          3             2         1           7.00              2

MRVDetail:

      MRVDetailID       AcceptedQty         PODetailID
     --------------    -------------       ------------
          1               3.00                  3
          2               4.00                  3
          3               10.00                 4

@Detail://这是一个表变量

      PODetailID           POQuantity
     ------------         ------------
          3                   7

这里,基于以上3个表格。我想更新PODetail StatusID = 4 MRVDetail的SUM(AcceptedQty)用于PODetailID =表变量@PODetail的POQuantity到特定的PODetailID。

如何实现这一目标?

我已尝试过以下更新声明。但它根本不起作用。这该怎么做?请帮帮我。

    UPDATE 
    PODetail
SET 
    PODetail.StatusID = 4
FROM 
        PODetail 
INNER JOIN @Detail P ON PODetail.PODetailID = P.PODetailID
INNER JOIN MRVDetail ON MRVDetail.PODetailID = P.PODetailID
WHERE 
(SELECT SUM(AcceptedQty) FROM MRVDetail WHERE MRVDetail.PODetailID = P.PODetailID) = P.POQuantity 
    AND PODetail.POID = 2

1 个答案:

答案 0 :(得分:2)

UPDATE PODetail
SET    StatusID = 4
WHERE  PODetailID IN (SELECT d.PODetailID
                      FROM   @Detail AS d
                      INNER JOIN (SELECT PODetailID,
                                         SUM(AcceptedQty) AS Qty
                                  FROM   MRVDetail
                                  GROUP BY PODetailID) AS m
                      ON d.PODetailID = m.PODetailID AND 
                         d.POQuantity = m.Qty)  

http://data.stackexchange.com/stackoverflow/q/112195/