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
相关推荐
尚学教辅学习资料3 小时前
SSM从入门到实战:2.5 SQL映射文件与动态SQL
数据库·sql·动态sql·sql映射
WayneJoon.H3 小时前
CTFSHOW | 其他篇题解(一)web396-web416
sql·安全·web安全·网络安全·php
大新屋3 小时前
MongoDB 分片集群把非分片集合转成分片集合
数据库·mongodb
Python代狂魔4 小时前
Redis
数据库·redis·python·缓存
柠檬茶AL4 小时前
36 NoSQL 注入
数据库·nosql·postman
-XWB-4 小时前
PostgreSQL诊断系列(2/6):锁问题排查全攻略——揪出“阻塞元凶”
数据库·postgresql
XiaoMu_0015 小时前
【MongoDB与MySQL对比】
数据库
做科研的周师兄5 小时前
【机器学习入门】1.2 初识机器学习:从数据到智能的认知之旅
大数据·数据库·人工智能·python·机器学习·数据分析·机器人
qq_364371726 小时前
基于 Redis + JWT 的跨系统身份共享方案
数据库·redis
技术与健康6 小时前
LLM实践系列:利用LLM重构数据科学流程04 - 智能特征工程
数据库·人工智能·重构