使用带有多个select语句的update

时间:2014-06-06 21:59:01

标签: sql sql-server

 update opportunitysrcfact set [Last_Amount]=  (select  c.amount from

 (select a.amount,b.id from

   ( Select * from OpportunitySrcFact    where fiscalweekqtr = '2013 Q3 5')  a
   inner join 
   ( Select * from opportunitysrcfact    where fiscalweekqtr = '2013 Q3 6')  b
  on a.id = b.id 
   where a.amount != b.amount )  c )
   where opportunitysrcfact.id = c.id and opportunitysrcfact.fiscalweekqtr ='2013 Q3 6'

上面是给出错误的查询coz c.id是一个多级标识符,不能在最后一个where子句中使用。 我需要使用给定的商机ID更新行中的选定金额

1 个答案:

答案 0 :(得分:1)

由于您使用的是sql server,因此可以使用' With'带有更新语句的子句。

尝试这个:

 with c as
   (
    select a.amount as amount,b.id as id from

       ( Select * from OpportunitySrcFact    where fiscalweekqtr = '2013 Q3 5')  a
        inner join 
       ( Select * from opportunitysrcfact    where fiscalweekqtr = '2013 Q3 6')  b
        on a.id = b.id 
        and a.amount != b.amount 
   )
   update opportunitysrcfact 
   set Last_Amount=  c.amount
   from opportunitysrcfact inner join c
   on opportunitysrcfact.id = c.id and opportunitysrcfact.fiscalweekqtr ='2013 Q3 6';