The Employee
table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.
+----+-------+--------+-----------+ | Id | Name | Salary | ManagerId | +----+-------+--------+-----------+ | 1 | Joe | 70000 | 3 | | 2 | Henry | 80000 | 4 | | 3 | Sam | 60000 | NULL | | 4 | Max | 90000 | NULL | +----+-------+--------+-----------+
Given the Employee
table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager.
+----------+ | Employee | +----------+ | Joe | +----------+
解题:
1.复制表,分别为t1,t2
2.找出两表中id 与 managerid相同,并且雇员工资更高的名字
3. 将name 改为 Employee
select t1.name as ‘Employee‘ from
Employee as t1,
(select * from Employee) as t2
where
t1.managerid = t2.id
and
t1.salary > t2.salary
此处需要注意的是:manager 应该是id的直系manager,起初我的思路是找到 ManagerId is null 的数据,放到 表 t2中,然后继续按照步骤比较两个表中数据,但这就会出现雇员1 可能有 manager1,但是同时manager1 也会有manager2 作为他的manager,这就会导致我表t2中的manager数据有遗漏。导致结果错误。
错误写法:
select t1.name as ‘Employee‘ from
Employee as t1,
(select * from Employee where managerid is null) as t2
where
t1.managerid = t2.id
and
t1.salary > t2.salary