[LeetCode][SQL]Department Highest Salary

Department Highest Salary

The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id.

+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
+----+-------+--------+--------------+

The Department table holds all departments of the company.

+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+

Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, Max has the highest salary in the IT department

and Henry has the highest salary in the Sales department.

+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| Sales      | Henry    | 80000  |
+------------+----------+--------+

https://leetcode.com/problems/department-highest-salary/

 

 

 


 

 

 

一开始去找工资比所有人高的人,当雇员表只有一个人的时候结果就不对了。

1 # wrong answer !!!
2 select D.Name, E1.Name, E1.Salary from Employee E1, Employee E2, Department D 
3 where E1.DepartmentId = E2.DepartmentId and E1.Salary >= E2.Salary
4     and E1.DepartmentId = D.Id

于是反过来找,先找出工资比任意一个人低的所有人组成子表,目标员工不在子表中。

1 select D.Name, E.Name, E.Salary from Employee E, Department D  
2 where E.DepartmentId = D.Id and
3 E.Id not in
4 (
5     select E1.Id from Employee E1, Employee E2
6     where E1.DepartmentId = E2.DepartmentId and E1.Salary < E2.Salary
7 )

 

 

 
 
posted @ 2015-06-22 22:30  `Liok  阅读(407)  评论(0编辑  收藏  举报