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
相关推荐
MetaLite36 分钟前
SpringBoot接口分层规范-外网网关内部服务与参数边界
java·数据库·spring boot
Wang's Blog2 小时前
Java框架快速入门: Spring Security+OAuth2之元注解简化权限表达式
java·数据库·spring
蓝速科技4 小时前
医院导诊 AI 数字人一体机场景适配与落地指南丨蓝速科技
运维·数据库·人工智能·科技·自然语言处理·技术分享
QYR-分析4 小时前
重轨受电弓行业深度报告:市场格局、技术迭代与发展前景
大数据·数据库·人工智能
泡泡鱼(敲代码中)5 小时前
MySQL基础学习笔记:从数据模型到DDL全掌握
开发语言·数据库·笔记·学习·mysql
l1t6 小时前
DeepSeek总结的chdb-core v26.7.3发版说明
数据库·clickhouse·oracle
冰暮流星6 小时前
mysql之表子查询
数据库·mysql
Full Stack Developme7 小时前
CRM相关库表设计
数据库
步行cgn7 小时前
Spring 注入 Map 集合详解
数据库·python·spring
风跟我说过她8 小时前
SQL 一键转经典 Chen 风格 ER 图:开源 CLI + 在线工具 + Agent Skill
数据库·python·sql·开源·开源软件