我在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的标志需要是&#39; Y&#39;因为他是该部门最大生效日期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'
如何解决这个问题?
答案 0 :(得分:0)
您可以使用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小提琴修复了拼写错误。