sql:如何获取最近的记录

rn0zuynd  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(355)

我需要帮助。如何获取两个单独表的最新记录?表1是员工记录表,其中包含员工编号和员工姓名。表2是包含员工编号、地址1、地址2、县、市、国家、邮政编码和生效日期的地址表。
如何根据最新日期从两个表中获取最新数据?
遗憾的是,我的sql不起作用。不知何故,我得到了一个错误“错误语法附近的't3'”。我搞不懂那不正确的语法是什么。请帮忙。谢谢您!

SELECT  T1.EmpNumber,
        T1.EmpName,
        T2.City,
        T2.Country,
        T2.EffDate

FROM    EmployeeTable T1
        LEFT OUTER JOIN AddressTable T2
        ON T1.EmpNumber = T2.EmpNumber
        AND T2.EffDate = (
                 SELECT EmpNumber,
                        MAX (EffDate) as RecentDate
                 FROM AddressTable
                 GROUP BY EmpNumber) T3 ON T1.EmpNumber = T3.EmpNumber AND T2.EffDate = T3.RecentDate
i7uq4tfw

i7uq4tfw1#

对于这个最大的每组n个问题,一个可移植的解决方案是使用子查询进行过滤-这也是您尝试的精神:

select e.employee_name, a.*
from  EmployeeTable e
inner join AddressTable a on a.employee_number = e.employee_number
where a.effective_date = (
    select max(a1.effective_date) 
    from AddressTable a1 
    where a1.employee_number = e.employee_number
)

如果您想允许没有地址的员工,那么您可以在 on a条款 left join :

select e.employee_name, a.*
from  EmployeeTable e
left join AddressTable a 
    on  a.employee_number = e.employee_number
    and a.effective_date = (
        select max(a1.effective_date) 
        from AddressTable a1 
        where a1.employee_number = e.employee_number
    )

相关问题