leetcode - 数据库 - 184. 部门工资最高的员工 rank() + over()

      
      原题:https://leetcode-cn.com/problems/department-highest-salary/
      我自己做leetcode的数据库题目的解题记录:
              解题目录 https://blog.csdn.net/weixin_42845682/article/details/105196004
      
      

题目描述:

      Employee 表包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id。

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

      Department 表包含公司所有部门的信息。

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

      编写一个 SQL 查询,找出每个部门工资最高的员工。例如,根据上述给定的表格,Max 在 IT 部门有最高工资,Henry 在 Sales 部门有最高工资。

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

      

答案:

第一种答案

      一开始感觉这道题很简单,后来发现有点难。如果让我来设计表结构,我肯定要把薪酬表和员工个人信息表分开。

select 
    department Department,
    e1.name Employee,
    tmp.salary Salary  
from employee e1
join (
	select
	    d.name department,
	    d.id id,
	    max(salary) salary 
	from employee e 
	join department d on e.departmentId = d.id 
	group by d.name,d.id 
) tmp on e1.salary = tmp.salary and e1.departmentId = tmp.id 
group by tmp.department, e1.name 

      虽然写出来了,也通过测试了,但是看着总觉得哪里怪怪的。
      思路是:先找出部门最高的工资,然后用部门和工资去join,employee表(因为有可能出现几个部门最高工资是一样的,所以用部门加工资)。
      但是怎么说呢,总感觉显示员工名字怪怪的,不考虑重名吗?而且题目也没说,如果一个部门有两个人并列工资最高应该怎么显示,烦。

第二种答案

      其实这种分段排序,用row_number()也能做。

select
    dname department,
    ename employee,
    salary 
from(
select
    d.name dname,
    e.name ename,
    e.salary,
    row_number() over(partition by d.name order by salary desc) row_num 
from employee e 
join department d on e.departmentId=d.id 
) tmp
where row_num = 1

      提交的时候,出错了。看了一下,预期输出结果:如果部门有两个工资一样高的,那么要把两个人都输出。那row_number()肯定是不行了。。。
      不过也好改,改成dense_rank()或者rank()都行。

select
    dname department,
    ename employee,
    salary 
from(
select
    d.name dname,
    e.name ename,
    e.salary,
    dense_rank() over(partition by d.name order by salary desc) row_num 
from employee e 
join department d on e.departmentId=d.id 
) tmp
where row_num = 1

      吐槽一下:这些重合的数据怎么处理没有具体的说明;oracle提交也是真的麻烦…一直超时
      得瑟一下:
在这里插入图片描述
      看来我写的这个,效率还蛮高的。

      
      
      
      
      

扫描二维码关注公众号,回复: 10664282 查看本文章
发布了48 篇原创文章 · 获赞 36 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/weixin_42845682/article/details/105437193