我想基于table2更新table1,table2有一个公共字段employee_ID。我总是在table1中有唯一的employee_ID但在table2中它可能包含具有相同employee_ID的重复记录。
我在table2中有另一列插入了modified_date。我想根据employee_id和最近修改日期更新table1员工姓名和table2员工姓名。
我有多列要使用相同类型的条件进行更新。任何想法,到目前为止我都试过。
这是查询,我使用了内连接,
ssql = "Update Table1 INNER JOIN Table2
ON Table1.employee_id= Table2.employee_id
SET Table1.type= Table2.type"
任何帮助将不胜感激
答案 0 :(得分:1)
尝试此查询
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)
答案 1 :(得分:1)
您需要一个中间步骤将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