如何找到在经理面前加入其部门的员工的人员

时间:2014-10-10 23:55:58

标签: sql oracle

我试图找出在经理面前加入的员工。我怎么解决这个问题? 我的架构如下。

Employee (EmpId, DeptId,MgrId,Salary, DateOfJoining)

第一个解决方案: -

SELECT DISTINCT e.EmpId AS Empid
FROM Employee e
INNER JOIN Employee m
ON e.MgrId = m.Empid
AND e.DateofJoining < m.DateOfJoining;

第二个解决方案: -

SELECT A.EmpId,A.DateOfJoining
FROM Employee A,
(
SELECT DISTINCT e.EmpId,m.Empid AS MgrID,m.DOJ 
FROM Employee e,Employee m 
WHERE e.MgrId = m.Empid
) B
WHERE A.EmpId = B.EmpId 
  AND A.DateOfJoining < B.DateOfJoining;

2 个答案:

答案 0 :(得分:0)

你需要一个自我加入才能做到这一点。

SELECT e.*  --* to return all details, if needed
FROM Employee e
LEFT JOIN Employee m ON e.MgrId = m.Empid
WHERE m.Empid is not null
AND e.DateofJoining < m.DateOfJoining;

或者你可以用内连接来做到这一点 -

SELECT e.*  --* to return all details, if needed
FROM Employee e
INNER JOIN Employee m ON e.MgrId = m.Empid AND e.DateofJoining < m.DateOfJoining;

将WHERE子句条件放在连接中的区别在于连接只会在满足条件的情况下发生,而不是在1条件上连接然后进行过滤。就个人而言,我尽可能少地尝试这样做。

答案 1 :(得分:0)

问题是:Display all the employees who have joined before their managers

答案是:

SELECT E1.ENAME FROM EMP E1,EMP E2 
WHERE E1.MGR=E2.EMPNO 
AND E1.MGR < E2.MGR;