用SUM()更新

时间:2014-08-20 19:47:42

标签: sql sql-server-2008

我有一个类似于下面的表结构

Table1

BatchID     Quantity     ProductID
1           10           1

1           10           1

1           20           2

我需要按产品ID分组并获取最大数量,然后将其相加并更新table2。因此table2中的结果将是

Table2

BatchID    Total
1          30

我提出的更新查询是

UPDATE T2
SET
Table1.Total = Sum(sub.quantity)
FROM Table2 T2
INNER JOIN 
    (SELECT 
        MAX(T1.Quantity) quantity,
    FROM Table1 T1
    GROUP BY T1.ProductID,Ti.Quantity) AS sub ON sub.BatchID= T1.BatchID
WHERE T1.BatchID = 1

当我运行此查询时,它会抛出此错误 “聚合可能不会出现在UPDATE语句的集合列表中。”

请帮我修复此错误。

3 个答案:

答案 0 :(得分:1)

再次嵌套子查询...我认为mssql可以处理它。 :

UPDATE T2
SET
Table1.Total = sub.quantity
FROM Table2 T2
INNER JOIN 
select sum(a.quantity) as quantity
from
(SELECT 
    MAX(T1.Quantity) quantity,
FROM Table1 T1
GROUP BY T1.ProductID,Ti.Quantity)a) AS sub ON sub.BatchID= T1.BatchID
WHERE T1.BatchID = 1

答案 1 :(得分:0)

update table2 
    set total = coalesce((select sum(max_quantity)
                          from (
                              select max(Quantity) as max_quantity 
                              from table1 
                              where table1.batchid = table2.batchid 
                              group by productid
                         ) as tmp), total);

答案 2 :(得分:0)

这可以解决您的问题:

UPDATE  a
SET     Total = b.Quantity
FROM    Table2 a
        INNER JOIN ( SELECT x.BatchID ,
                            SUM(y.Quantity) AS Quantity
                     FROM   Table2 x
                            INNER JOIN ( SELECT z.BatchID ,
                                                z.ProductID ,
                                                MAX(z.Quantity) Quantity
                                         FROM   Table1 z
                                         WHERE  z.BatchID = 1
                                         GROUP BY z.BatchID ,
                                                z.ProductID
                                       ) y ON y.BatchID = x.BatchID
                     GROUP BY y.BatchID
                   ) b ON a.BatchID = b.BatchID