sql - SQL中的第N个薪水
问题描述
我试图了解下面的查询,它是如何工作的。
SELECT *
FROM Employee Emp1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary
)
假设我有5
不同的薪水,并希望获得3rd
最高的薪水。那么内部查询将首先运行然后外部查询?
我很困惑它是如何在 sql 引擎中完成的。很想知道。因为如果它3rd
最大 then 3-1 = 2
,所以也2
需要与内部计数匹配。如何操作内部计数。
谁能解释它的工作原理..?
解决方案
The subquery is correlated subquery, so it conceptually executes once for each row in the outer query (database optimizations left apart).. What it does is count how many employees have a salary greater than the one on the row in the outer query: if there are 2 employee with a higher salary, then you know that the employee on the current row in the outer query has the third highest salary.
Another way to phrase this is to use row_number()
for this:
select *
from (
select
e.*,
row_number() over(order by salary desc) rn
from employee e
) t
where rn = 3
Depending on how you want to handle duplicates, dense_rank()
might also be an option.
推荐阅读
- python - 在单词列表中找到与给定单词距离最小的单词
- events - 在 KONVAJS 中全局过滤事件
- java - 获取 LocalContainerEntityManagerFactoryBean 以执行特定的架构和数据脚本
- android - 当镜头在 API < 29 中为单色时,使用 Camera2 确定
- json - 将带有字符串的列表转换为json pyspark
- javascript - 如何在adonisjs中进行动态授权?
- json - VB.Net_Having 从 JSON 读取令牌时出现问题
- kotlin - CharBuffer 到字符串?
- docker - Docker-compose 卷模式选项
- spring - propertySources 显示为空(Spring Cloud Config)