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
相关推荐
这个DBA有点耶41 分钟前
AI写的SQL跑崩了生产库,这锅谁背?
数据库·人工智能·程序员
镜舟科技1 小时前
Databricks 再提 LTAP,AI 时代的数据底座为何重回大一统叙事?
数据库·架构·agent
Databend2 小时前
从湖仓升级为 Agent 时代的数据控制面,Snowflake 和 Databricks 有哪些布局
大数据·数据库·agent
ClouGence5 小时前
SQL Server CDC 能放到 Always On 备库读吗?一文讲透原理与实践
数据库·sql server
先吃饱再说1 天前
存储的进化:从 MySQL 到浏览器缓存,数据到底住在哪?
数据库
Nturmoils1 天前
字段太多看不全,ksql 的展开模式和输出控制怎么用
数据库·后端
Databend1 天前
Agent 轨迹分析与归因的数据工程实践
大数据·数据库·agent
这个DBA有点耶1 天前
SQL改写进阶:标量子查询的“隐形代价”与消除实战
数据库·mysql·架构
smallyoung1 天前
数据库乐观锁深度解析:MySQL、PostgreSQL 实战 + Spring Boot 集成指南
数据库·mysql·postgresql
parade岁月1 天前
MySQL JOIN解析:朴实无华但食之有味
数据库·后端