【问题标题】:Update table1 from table2 value by recent date按最近日期从 table2 值更新 table1
【发布时间】:2017-10-03 10:03:12
【问题描述】:

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

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

我有多个列要更新为相同类型的条件。任何想法,到目前为止我都试过了。

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

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

任何帮助将不胜感激

【问题讨论】:

  • 您的查询有什么问题?

标签: sql ms-access vba ms-access-2010


【解决方案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)

【讨论】:

  • 您好,感谢您的回复。此处不知道修改日期。它必须从具有相同员工 ID 的可用记录中获取最近的日期记录。例如,如果日期类似于 01-jan-2017 和 01-jan-2018,那么它必须选择 01-jan-2018 记录。
  • 我尝试了 Vivek 的解决方案。它工作正常。我还没有尝试缩进答案。无论如何,非常感谢!!!
【解决方案2】:

您需要一个中间步骤来将 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

【讨论】:

  • 您好,此处列出的查询适用于一个日期列。如何更改查询以排序并在两个日期列中包含最新记录并选择记录
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
相关资源
最近更新 更多