SQL更新基于同一个表中的值

时间:2018-02-19 20:18:34

标签: sql join sql-update

我试图将这两个问题放在一起,但我不确定如何。我试图将同一个预算表中的值从去年的版本复制到今年版本,基于它们具有相同的帐户和工作订单。

update tablename 
set depreciation = x.depreciation, 
    profile = x.profile, 
    description = x.description 
where version = '2019OP' 
     and account = x.account 
     and workorder = x.workorder

(select * from tablename where version = '2018OP' and batch = '') x

我在这个论坛上发现了与此类似的其他问题,但我无法得到适合我的答案。

谢谢

编辑 - 这是SQL Server 2012,兼容级别是SQL Server 2008(100) 在SSMS中使用SQL

3 个答案:

答案 0 :(得分:0)

像这样的东西

update tablename from tablename
set depreciation = x.depreciation, 
    profile = x.profile, 
    description = x.description 
inner join tablename x on x.version = '2019OP' 
     and tablename.account = x.account 
     and tablename .workorder = x.workorder

答案 1 :(得分:0)

您没有指定RDBMS。在Sql Server中,这应该工作...

UPDATE x1 
SET x1.depreciation = x.depreciation, 
    x1.profile = x.profile, 
    x1.description = x.description 
FROM tablename x1
INNER JOIN tablename x ON x1.account = x.account AND x1.workorder = x.workorder
WHERE x1.version = '2019OP' 
     AND x.version = '2018OP' AND x.batch = ''

答案 2 :(得分:-1)

    update tn set tn.depreciation = ly.depreciation, tn.profile = ly.profile, tn.description = ly.description
    FROM tablename  as tn INNER JOIN 
    (
     SELECT 
        account ,
        workorder,
       depreciation,
       profile ,
      description 
     FROM tablename AS  
     where version = '2018OP'  and batch = ''
     ) AS ly  ON ly.account  = tn.account   AND  ly.workorder  = tn.workorder    
     tn.version = '2019OP'