欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL实现LeetCode(184.系里最高薪水)

程序员文章站 2022-06-24 19:56:17
[leetcode] 184.department highest salary 系里最高薪水the employee table holds all employees. every employe...

[leetcode] 184.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  |
+------------+----------+--------+

这道题让给了我们两张表,employee表和department表,让我们找系里面薪水最高的人的,实际上这题是second highest salarycombine two tables的结合题,我们既需要联合两表,又要找到最高薪水,那么我们首先让两个表内交起来,然后将结果表需要的列都标明,然后就是要找最高的薪水,我们用max关键字来实现,参见代码如下:

解法一:

select d.name as department, e1.name as employee, e1.salary from employee e1
join department d on e1.departmentid = d.id where salary in 
(select max(salary) from employee e2 where e1.departmentid = e2.departmentid);

我们也可以不用join关键字,直接用where将两表连起来,然后找最高薪水的方法和上面相同:

解法二:

select d.name as department, e.name as employee, e.salary from employee e, department d
where e.departmentid = d.id and e.salary = (select max(salary) from employee e2 where e2.departmentid = d.id);

下面这种方法没用用到max关键字,而是用了>=符号,实现的效果跟max关键字相同,参见代码如下:

解法三:

select d.name as department, e.name as employee, e.salary from employee e, department d
where e.departmentid = d.id and e.salary >= all (select salary from employee e2 where e2.departmentid = d.id);

类似题目:

second highest salary

combine two tables

到此这篇关于sql实现leetcode(184.系里最高薪水)的文章就介绍到这了,更多相关sql实现系里最高薪水内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!