【问题标题】:SQL update based on values in same table基于同一表中的值的 SQL 更新
【发布时间】:2018-02-19 20:18:33
【问题描述】:

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

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

【问题讨论】:

  • 您使用的是什么 RDBMS? SQL Server、MySQL、Oracle、Postgres 等?它们的语法略有不同。
  • 以下答案可能有效,也可能无效,因为您没有指定。一旦您让我们知道您正在使用哪个 RDBMS,我们就可以相应地投票和反对。

标签: sql join sql-update


【解决方案1】:

类似的东西

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

【讨论】:

    【解决方案2】:

    您没有指定 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 = ''
    

    【讨论】:

      【解决方案3】:
          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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多