MS Access:如何找到状态为“工作”或“已恢复”的最新日期的员工?

问题描述

tbl_emp_mast

emp_no emp_last_name emp_first_name
1      smith          john
2      doe            jane
3      case           justin

tbl_emp_st

emp_no  st_date      emp_st
1       10/01/2020    WORKING
1       10/05/2020    QUIT
1       10/10/2020    REINSTATED
2       10/07/2020    QUIT
3       10/02/2020    WORKING

出于表格中组合框的目的,我只希望那些当前正在工作的员工。因此,查询结果中应该有员工1和3。 我尝试过:

SELECT tbl_emp_mast.emp_no AS tbl_emp_mast_emp_no,tbl_emp_mast.emp_last_name & "," & tbl_emp_mast.emp_first_name AS Employee,tbl_emp_st.st_date,tbl_emp_st.emp_st
FROM tbl_emp_mast INNER JOIN tbl_emp_st ON tbl_emp_mast.[emp_no] = tbl_emp_st.[emp_no];

谢谢。

解决方法

嗯。 。 。我认为您需要最新的emp_st。如果是这样,那么我认为:

select es.*
from tbl_emp_st as es
where es.st_date = (select max(es2.st_date)
                    from tbl_emp_st as es2
                    where es2.emp_no = es.emp_no
                   ) and
      es.emp_st in ('WORKING','REINSTATED');
,

您应该添加WHERE子句,以检查每个tbl_emp_st的最新日期是否是其中emp_st不等于'QUIT'的行:

SELECT m.emp_no AS tbl_emp_mast_emp_no,m.emp_last_name & ',' & m.emp_first_name AS Employee,s.st_date,s.emp_st
FROM tbl_emp_mast AS m INNER JOIN tbl_emp_st AS s
ON m.emp_no = s.emp_no
WHERE s.st_date = (SELECT MAX(st_date) FROM tbl_emp_st WHERE emp_no = m.emp_no)
    AND s.emp_st <> 'QUIT'

结果:

tbl_emp_mast_emp_no   Employee        st_date       emp_st
1                     smith,john     10/10/2020    REINSTATED
3                     case,justin    10/02/2020    WORKING