如何查看员工在部门最晚生效日期是不是为部门经理?
Posted
技术标签:
【中文标题】如何查看员工在部门最晚生效日期是不是为部门经理?【英文标题】:How to check if an employee is the manager of a department at the department's latest effective date?如何查看员工在部门最晚生效日期是否为部门经理? 【发布时间】:2015-06-20 13:24:20 【问题描述】:我在 SQL Oracle 的视图中编码条件时遇到问题。
我有 2 个表格,这里是您需要的字段名称:
EMPLOYEE_TBL (employee_id)
DEPARTMENT_TBL (department_id, manager_id, effective_date, active_status)
我必须在 SELECT CASE 中编写以下条件:
FLAG = 'Y' if the employee is the manager of AT LEAST ONE department at the department's
latest (max) effective date and that the department has active_status = 'A'
at its max effective date
FLAG = 'N' otherwise
这是我目前所拥有的,但它并没有达到我想要的效果:
SELECT A.EMPLOYEE_ID, B.EFFECTIVE_DATE, B.ACTIVE_STATUS,
CASE WHEN EXISTS (SELECT DISTINCT Z.MANAGER_ID FROM DEPARTMENT_TBL Z
WHERE Z.MANAGER_ID = B.MANAGER_ID
AND Z.DEPARTMENT_ID = B.DEPARTMENT_ID
AND Z.MANAGER_ID = A.EMPLOYEE_ID /* this is the condition */
AND Z.EFFECTIVE_DATE = (SELECT MAX(Y.EFFECTIVE_DATE)
FROM DEPARTMENT_TBL Y
WHERE Y.DEPARTMENT_ID = Z.DEPARTMENT_ID
AND Y.EFFECTIVE_DATE <= SYSDATE)
AND Z.ACTIVE_STATUS = 'A')
THEN 'Y' ELSE 'N' END AS FLAG
FROM EMPLOYEE_TBL A LEFT JOIN DEPARTMENT_TBL B
ON A.employee_id = B.manager_id
这里是 SQLFiddle:http://sqlfiddle.com/#!4/241d99/1
遗留问题:员工 35 的标志必须为“Y”,因为他是部门 D7777 在部门最大生效日期的经理。
这里是 DEPARTMENT_TBL:
DEPARTMENT_ID MANAGER_ID EFFECTIVE_DATE EFFECTIVE_STATUS
D1273 35 2006-01-01 A
D1273 35 2011-12-21 A -- here flag of 35 is 'N'
D1273 04 2012-03-05 A
D1000 04 2012-12-12 A
D7777 04 2009-05-14 A
D7777 35 2011-09-26 A -- but here flag of 35 is 'Y'
如何解决这个问题?
【问题讨论】:
你是对的,但是当我想返回所有员工并且只是让标志表明他们是否仍然是经理时,那只会返回作为经理的员工 @jpw 我刚刚发现了另一个问题。请检查我对原始帖子和新 SQLFiddle 所做的编辑。 【参考方案1】:您可以使用row_number()
获取部门的最新记录。这大大简化了查询:
select e.*,
(case when d.department_id is not null then 'Y' else 'N' end) as isManager
from employee_tbl e left join
(select d.*,
row_number() over (partition by d.department_id
order by d.effective_date desc) as seqnum
from department_tbl d
where d.effective_date < sysdate
) d
on e.department_id = d.department_id and d.active_status = 'A' and
seqnum = 1;
Here's 修正了错字的 SQL Fiddle。
【讨论】:
@jpw 。 . .这很容易添加到on
子句中。
您对 d.effective_status 的查询似乎有误...查看此处sqlfiddle.com/#!4/241d99/4
只需将 e.department_id = d.department_id 和 d.active_status = 'A' 和 seqnum = 1 上的 d.effective_status
更改为 d.active_status
以上是关于如何查看员工在部门最晚生效日期是不是为部门经理?的主要内容,如果未能解决你的问题,请参考以下文章