【问题标题】:Update multiple columns from a specific row in another table从另一个表中的特定行更新多个列
【发布时间】:2020-06-30 00:11:45
【问题描述】:

我已经看到从联接更新多行的示例,但在这种情况下,联接会产生多个匹配的行,我需要一个特定的行(最早的 UpdatedDate 行)。

表格示例:

[机器人]

RobotNumber         RobotName    RobotColor      UpdatedDate   
1                   XA01         Red             01/01/2020
2                   B1205        Purple          02/02/2020
3                   ZP344        Orange          03/03/2020

[机器人审计表]

RobotNumber         RobotName    RobotColor      UpdatedDate   
1                   XA01         Yellow          1/1/2019
1                   XA01         Red             2/2/2020

我想用 RobotAuditTable 中最早更新日期行中的值(RobotName,RobotColor)更新 RobotName XA01。

我尝试过使用连接和子查询的方法,但无法正确获取语法和条件。

【问题讨论】:

    标签: sql sql-server tsql join


    【解决方案1】:

    你可以使用apply:

    update r
        set r.robotname = rat.robotname,
            r.robotcolor = rat.robotcolor        
        from robot r cross apply
             (select top (1) rat.*
              from robotaudittable rat
              where rat.robotnumber = r.robotnumber
              order by rat.updateddate asc
             ) rat;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 2015-04-02
      • 1970-01-01
      相关资源
      最近更新 更多