更新声明帮助

时间:2015-06-06 18:57:35

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

我已编写此查询以获取新值

select
    ol.ordernumber, 
    sum(ol.Quantity * ol.each * ol.OriginalPrice) + s.ShippingCost as New Cost
from 
    orderlines ol, orders o, ShippingMethods s
where 
    ol.ordernumber = o.OrderNumber
    and o.ShippingMethod = s.ShippingMethod
    and CreateDate between '2015-05-01' and '2015-05-31'
group by 
    ol.OrderNumber, s.ShippingCost

我想用像

这样的声明进行更新
update Orders
set TotalRedoCostIncludingShipping = NewCost 

我只是不确定如何将两个查询链接在一起以按订单号更新订单表。

2 个答案:

答案 0 :(得分:1)

尝试类似:

update o
set TotalRedoCostIncludingShipping = (
  select sum(ol.Quantity * ol.each * ol.OriginalPrice) + s.ShippingCost
  from orderlines ol, ShippingMethods s
  where ol.ordernumber = o.OrderNumber
  and o.ShippingMethod = s.ShippingMethod
  and CreateDate between '2015-05-01' and '2015-05-31'
  Group by s.ShippingCost
)
from Orders o

问候,达蒙

答案 1 :(得分:0)

的内容
with cte as 
(
  select o.OrderNumber, sum(ol.Quantity * ol.each * ol.OriginalPrice) + s.ShippingCost newcost
    from orderlines ol join orders o
      on ol.ordernumber = o.OrderNumber join ShippingMethods s
      on o.ShippingMethod = s.ShippingMethod
   where CreateDate between '2015-05-01' and '2015-05-31'
   group by ol.OrderNumber, s.ShippingCost    
)
update o
   set o.TotalRedoCostIncludingShipping = c.newcost
  from cte c join orders o
    on c.OrderNumber = o.OrderNumber