d202552-sql

一、184. 部门工资最高的员工 - 力扣(LeetCode)

要找到每个部门工资最高的

使用窗口函数 加排序函数

排序函数用rank dense_rank都行 把最高相同的找出来就行

sql 复制代码
select *,
dense_rank() over(partition by departmentId  order by Salary desc) as 'rank' 
from Employee

有没有朋友 也想过为啥这里不能直接用where

sql 复制代码
select *,
dense_rank() over(partition by departmentId  order by Salary desc) as 'rank' 
from Employee
where rank = 1
1. ​​SQL 执行顺序​

SQL 查询的逻辑执行顺序为:

  1. FROM → 2. WHERE → 3. GROUP BY → 4. HAVING → 5. SELECT → 6. ORDER BY
    ​关键点​WHERE 子句在 SELECT 之前执行,而 SELECT 中定义的别名(如 rank)此时尚未生成,因此无法被识别
    把上述那个表当成临时表,来进行两表连接
sql 复制代码
select d.name as 'Department',e.name as 'Employee',e.salary as 'Salary'
from Department d
join (select *,dense_rank() over(partition by departmentId  order by Salary desc) as 'rank' from Employee) e
on d.id = e.departmentId 
where e.rank = 1

搞定 说实话窗口函数真好用!!!!!!

二、185. 部门工资前三高的所有员工 - 力扣(LeetCode)

同理上题

但是这里的排序函数只能 **DENSE_RANK()​,**相同值分配相同排名,后续排名连续

where 里面的条件在加2个

sql 复制代码
select d.name as 'Department',e.name as 'Employee',e.salary as 'Salary'
from Department d
join (select *,dense_rank() over(partition by departmentId  order by Salary desc) as 'rank' from Employee) e
on d.id = e.departmentId 
where e.rank = 1 or e.rank = 2 or e.rank = 3

三、577. 员工奖金 - 力扣(LeetCode)

需要使用左连接或者右连接完全保留员工表的数据

sql 复制代码
select e.name,b.bonus
from Employee e left join Bonus b
on e.empId = b.empId 
where bonus < 1000 or bonus is null
相关推荐
jiayou641 天前
KingbaseES 实战:深度解析数据库对象访问权限管理
数据库
李广坤2 天前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
爱可生开源社区3 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
随逸1773 天前
《从零搭建NestJS项目》
数据库·typescript
加号34 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏4 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
李慕婉学姐4 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
百锦再4 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
tryCbest4 天前
数据库SQL学习
数据库·sql
jnrjian4 天前
ORA-01017 查找机器名 用户名 以及library cache lock 参数含义
数据库·oracle