mysql之部门工资前三的所有员工
发布日期:2021-07-27 04:53:01 浏览次数:5 分类:技术文章

本文共 1918 字,大约阅读时间需要 6 分钟。

题目叙述

在这里插入图片描述

要求

在这里插入图片描述

解法一:
注:mysql也可以用开窗函数,用法与hive略有区别

select d.name department,a.name name,a.salary from department d,(SELECT name,salary ,departmentid,Dense_rank() over(partition by departmentid order by salary desc) as ranking from  employee1 ) a where a.departmentid = d.id and a.ranking <= 3

此方法最为简单,看着不复杂,在此不做详细解释

解法二:自定义变量
简化问题(分步骤)
分解步骤的思路,可以依据必要存在的步骤进行分解
1.根据 部门 (升),薪水 (降) 顺序查询出每个部门的员工 (Department, Employee, Salary)

SELECT dep.Name Department, emp.Name Employee, emp.SalaryFROM Employee empINNER JOIN Department dep ON emp.DepartmentId = dep.IdORDER BY emp.DepartmentId, emp.Salary DESC

2.每个部门的员工根据薪水进行排序

由于原本没有排序的字段,所以这里就需要自定义变量补充一个字段出来

## 先(部门,薪水)去重,再 部门(升),薪水(降) 排序SELECT te.DepartmentId, te.Salary,       CASE             WHEN @pre = DepartmentId THEN @rank:= @rank + 1            WHEN @pre := DepartmentId THEN @rank:= 1       END AS RANKFROM (SELECT @pre:=null, @rank:=0)tt,     (## (部门,薪水)去重,根据 部门(升),薪水(降) 排序         SELECT DepartmentId,Salary         FROM Employee         GROUP BY DepartmentId,Salary         ORDER BY DepartmentId,Salary DESC     )te

组合步骤

组合步骤时,尽量将每个步骤变成一个 结果集(不存在二次查询)
再将所有步骤的 结果集进行关联,从而提高性能

SELECT dep.Name Department, emp.Name Employee, emp.SalaryFROM (## 自定义变量RANK, 查找出 每个部门工资前三的排名        SELECT te.DepartmentId, te.Salary,               CASE                     WHEN @pre = DepartmentId THEN @rank:= @rank + 1                    WHEN @pre := DepartmentId THEN @rank:= 1               END AS RANK        FROM (SELECT @pre:=null, @rank:=0)tt,             (## (部门,薪水)去重,根据 部门(升),薪水(降) 排序                 SELECT DepartmentId,Salary                 FROM Employee                 GROUP BY DepartmentId,Salary                 ORDER BY DepartmentId,Salary DESC             )te       )tINNER JOIN Department dep ON t.DepartmentId = dep.IdINNER JOIN Employee emp ON t.DepartmentId = emp.DepartmentId and t.Salary = emp.Salary and t.RANK <= 3ORDER BY t.DepartmentId, t.Salary DESC ## t 结果集已有序,根据该集合排序

转载地址:https://blog.csdn.net/qq_45292079/article/details/107378960 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:flink之检查点(checkpoint)和保存点(savepoint)的区别
下一篇:大数据面试题之sqoop

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年09月11日 14时29分33秒