📢📢📢📣📣📣
哈喽!大家好,我是【莫若心】,一位上进心十足的【大数据领域博主】!😜😜😜
擅长主流数据Oracle、MySQL、PG 运维开发
✨ 如果有对【数据库】感兴趣的【小可爱】,欢迎关注💞💞💞
❤️❤️❤️感谢各位大可爱小可爱!❤️❤️❤️
文章目录
🐴 1.SQL题目概述
LeetCode原题链接
表: Employee +--------------+---------+ | 列名 | 类型 | +--------------+---------+ | id | int | | name | varchar | | salary | int | | departmentId | int | +--------------+---------+ id是此表的主键列。 departmentId是Department表中ID的外键。 此表的每一行都表示员工的ID、姓名和工资。它还包含他们所在部门的ID。 表: Department +-------------+---------+ | 列名 | 类型 | +-------------+---------+ | id | int | | name | varchar | +-------------+---------+ id是此表的主键列。 此表的每一行都表示一个部门的ID及其名称。
🚀题目:
编写SQL查询以查找每个部门中薪资最高的员工。
按 任意顺序 返回结果表。
查询结果格式如下例所示。输入: Employee 表: +----+-------+--------+--------------+ | id | name | salary | departmentId | +----+-------+--------+--------------+ | 1 | Joe | 70000 | 1 | | 2 | Jim | 90000 | 1 | | 3 | Henry | 80000 | 2 | | 4 | Sam | 60000 | 2 | | 5 | Max | 90000 | 1 | +----+-------+--------+--------------+ Department 表: +----+-------+ | id | name | +----+-------+ | 1 | IT | | 2 | Sales | +----+-------+ 输出: +------------+----------+--------+ | Department | Employee | Salary | +------------+----------+--------+ | IT | Jim | 90000 | | Sales | Henry | 80000 | | IT | Max | 90000 | +------------+----------+--------+ 解释:Max 和 Jim 在 IT 部门的工资都是最高的,Henry 在销售部的工资最高。
🐴 2.解题思路
这个题中Employee和Department 存在主外键的关系,所以直接用内连接即可
因为工资的最高存在多个,所以可以考虑用group by 分组或者排序的方式
🐴 3.方法实现
🌈3.1 Oracle实现
m.Department as “Department”,
m.Employee as “Employee”,
m.Salary as “Salary”
from
(
SELECT b.name AS “DEPARTMENT”,
a.name AS “EMPLOYEE”,
a.Salary,
DENSE_RANK() OVER(partition by a.departmentId ORDER BY a.salary desc) rank
FROM Employee a,Department b
where a.departmentId = b.id
) m where rank = 1
🌈3.2 MySQL实现
select
m.Department,
m.Employee,
m.Salary
from (
SELECT b.name AS “Department”,
a.name AS “Employee”,
a.Salary,
DENSE_RANK() OVER w AS “rank”
FROM Employee a,Department b
where a.departmentId = b.id
WINDOW w AS (partition by a.departmentId ORDER BY a.salary desc)
) m where m.rank=1;
🐴 4.代码测试
🌈 Oracle执行代码,开始测试
与测试结果一致,测试成功!
🌈 MySQL执行代码,开始测试
与测试结果一致,测试成功!
🐴 5.知识点小结
MySQL8.0 中可以利用 DENSE_RANK()窗口函数实现并列的排序
🐴 6.如何成为SQL高手
学习IT邦德老师的专栏
https://blog.csdn.net/weixin_41645135/category_11653817.html
大家点赞、收藏、关注、评论啦 👇🏻👇🏻👇🏻
版权归原作者 莫若心 所有, 如有侵权,请联系我们删除。