使用union all更新多个列

时间:2018-10-14 14:51:01

标签: sql-server sql-server-2008-r2

我需要使用两个其他表的并集来更新一个表的多个列。

这里是一个例子:

UPDATE CustomerTrans 
SET SumQuantity = (SELECT SUM(x.Quantity)
                   FROM 
                       (SELECT * 
                        FROM InventoryTrans  
                        UNION ALL 
                        SELECT * 
                        FROM InventoryTranstemp) x 
                   JOIN
                       CustomerTrans a ON a.TrnDocumentID = x.TrnDocumentID),
    SumPrice = (SELECT SUM(x.Price)   
                FROM 
                    (SELECT * 
                     FROM InventoryTrans  
                     UNION ALL 
                     SELECT * 
                     FROM InventoryTranstemp) x 
                JOIN
                    CustomerTrans a ON a.TrnDocumentID = x.TrnDocumentID)

如您所见,两个选择完全相同。我该如何避免呢?

接受的答案也使用联接而不是联合

UPDATE CustomerTrans 
SET SumQuantity = (SELECT SUM(x.Quantity),
    SumPrice = (SELECT SUM(x.Price))
                FROM 
                    (SELECT * 
                     FROM InventoryTrans  
                     UNION ALL 
                     SELECT * 
                     FROM InventoryTranstemp) x 
                JOIN
                    CustomerTrans a ON a.TrnDocumentID = x.TrnDocumentID) 

使用此语句,我得到一个错误:

  

116级第1状态第11行的消息
  如果未使用EXISTS引入子查询,则只能在选择列表中指定一个表达式。

2 个答案:

答案 0 :(得分:1)

   with x as

   (
   select * from InventoryTrans 
   UNION ALL
    Select * from InventoryTranstemp
   )
   update CustomerTrans set 
  SumQuantity= (select sum (x.Quantity) from x 

   where CustomerTrans.TrnDocumentID=x.TrnDocumentID),

   sumPrice= (select sum (x.sumPrice) from x

   where CustomerTrans.TrnDocumentID=x.TrnDocumentID)

答案 1 :(得分:0)

尝试:

 with tmp as
(

   select f1.TrnDocumentID, f1.Quantity, f1.Price from InventoryTrans f1 inner join CustomerTrans f2 on f1.TrnDocumentID=f2.TrnDocumentID 
   UNION ALL
   Select f1.TrnDocumentID, f1.Quantity, f1.Price from InventoryTranstemp f1 inner join CustomerTrans f2 on f1.TrnDocumentID=f2.TrnDocumentID 
)
update f0
set f0.SumQuantity=sum (f1.Quantity), f0.SumPrice =sum (f1.Price)
from CustomerTrans f0 inner join tmp f1 on f0.TrnDocumentID=f1.TrnDocumentID