我有一个名为 view_att_tabulation 的表,它保存员工在给定日期的每日出勤信息,而 tbl_employ 保存有关员工的所有信息。我想检索给定日期所有活跃 = Y、状态为 1、employee_id 以“W”开头的员工的出勤情况。下面的代码对于今天和昨天总是可以正常工作,但对于之前的日期总是会抛出错误。对我哪里出错有什么建议吗?
SELECT emp_id, employ_id, employ_label, employ_name, employ_shortname, status, active_flag,
(SELECT
CASE
WHEN (
SELECT view_att_tabulation.emp_id FROM view_att_tabulation
WHERE view_att_tabulation.emp_id = tbl_employ.emp_id AND
employ_workdate = '2024-01-17' AND attendance_type LIKE 'PRESENT'
)
THEN 'PRESENT'
WHEN
(
SELECT view_att_tabulation.emp_id FROM view_att_tabulation
WHERE view_att_tabulation.emp_id = tbl_employ.emp_id AND
employ_workdate ='2024-01-17' AND attendance_type LIKE 'ABSENT'
)
THEN 'ABSENT'
ELSE ''
END
)AS employ_att
FROM tbl_employ
WHERE active_flag = 'Y' AND status = '1' AND employ_id LIKE 'W%'
ORDER BY employ_att, `tbl_employ`.`employ_id` ASC;
SELECT
tbl_employ.emp_id,
tbl_employ.employ_id,
tbl_employ.employ_label,
tbl_employ.employ_name,
tbl_employ.employ_shortname,
tbl_employ.status,
tbl_employ.active_flag,
CASE
WHEN view_att_tabulation.attendance_type = 'PRESENT' THEN 'PRESENT'
WHEN view_att_tabulation.attendance_type = 'ABSENT' THEN 'ABSENT'
ELSE ''
END AS employ_att
FROM
tbl_employ
LEFT JOIN
view_att_tabulation ON tbl_employ.emp_id = view_att_tabulation.emp_id
AND view_att_tabulation.employ_workdate = '2024-01-17'
WHERE
tbl_employ.active_flag = 'Y'
AND tbl_employ.status = '1'
AND tbl_employ.employ_id LIKE 'W%'
ORDER BY
employ_att, tbl_employ.employ_id ASC;
基于
LEFT JOIN
和 view_att_tabulation
,将子查询替换为 emp_id
上的 employ_workdate
。然后,我直接在主查询中使用 CASE
语句来根据 employ_att
确定 attendance_type
值。
这应该会简化您的查询,并可能有助于解决您在今天或昨天之前的日期所面临的问题。确保根据您的需要调整
WHERE
子句和 view_att_tabulation.employ_workdate
比较中的日期条件。