按最近日期从 table2 值更新 table1

Update table1 from table2 value by recent date

我想根据具有公共字段 employee_ID 的表 2 更新表 1。我在 table1 中总是有唯一的 employee_ID,但在 table2 中它可能包含具有相同 employee_ID 的重复记录。

我在表 2 中得到了另一列,其中插入了 modified_date。我想根据 employee_id 和最近修改日期用 table2 员工姓名更新 table1 员工姓名。

我有多个列要根据相同类型的条件进行更新。任何想法,这是我到目前为止尝试过的。

这是查询,我使用了内连接,

ssql = "Update Table1 INNER JOIN Table2 
ON Table1.employee_id= Table2.employee_id 
SET Table1.type= Table2.type"

任何帮助将不胜感激

试试这个查询

update t1 set t1.employee_name = t2.employee_name from table1 as t1
inner join table2 as t2 on t1.employee_id = t2.employee_id
where t2.Modified_date = (select Max(modified_date) from table2 as tb2 where 
tb2.employee_id = t2.employee_id group by tb2.employee_id)

您需要一个中间步骤将 Max(modified_date) 关联到每个 employee_id。

使用 CTE 表达式,您可以尝试这样的操作:

with
more_recent as (
    select
        employee_id,
        Max(modified_date) max_modified_date
    from
        table2
    group by
        employee_id    
)
update
    t1
set
    t1.employee_name = t2.employee_name
from
    table1 as t1
    inner join more_recent mr on 
        t1.employee_id = mr.employee_id
    inner join table2 as t2 on 
        mr.employee_id = t2.employee_id
        mr.max_modified_date = t2.modified_date