mysql - SQL中的第N个最大薪水查询

标签 mysql sql

我有一张 table ;包含 2 个字段,name 和 salary。我使用下面的脚本找到了第三个最高薪水。

SELECT DISTINCT sal 
FROM downtodate1.emp e1  
WHERE 3 = (SELECT COUNT(DISTINCT sal) FROM downtodate1.emp e2 WHERE e1.sal<= e2.sal);

我想知道它是如何工作的,为什么这里使用 3?

最佳答案

select distinct sal 
from downtodate1.emp AS e1  
where 3 = (
    select count(distinct sal) 
    from downtodate1.emp e2 
    where e1.sal <= e2.sal
);

假设您有一个这样的表:

sal
---
3
3
2
1
1
0

有了这部分

select distinct sal 
from downtodate1.emp AS e1 

你会得到结果

sal
---
3
2
1
0

这就是 4 个不同的薪水。

现在是子查询

    select count(distinct sal) 
    from downtodate1.emp e2 
    where e1.sal <= e2.sal

对主查询中的每一行执行。它计算低于或等于主查询中行的不同值的数量。所以这个的结果实际上是(但没有显示):

sal | count(distinct sal) where e1.sal <= e2.sal
------------------------------------------------
3     1
3     1
2     2
1     3
1     3
0     4

与主查询不同,您将得到以下结果:

sal | count(distinct sal) where e1.sal <= e2.sal
------------------------------------------------
3     1
2     2
1     3
0     4

WHERE条款3 = (/*subquery*/)你只会得到

sal | count(distinct sal) where e1.sal <= e2.sal
------------------------------------------------
1     3

这一行。所以结果是1 .

希望现在一切都清楚了。

关于mysql - SQL中的第N个最大薪水查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15474216/

相关文章:

MySQL 相同列与不同行的连接

mysql - 如果逗号则获取子字符串,否则返回整个字符串

mysql - 如何在较新版本的 MySQL 中以编程方式验证密码?

sql - COUNT(*) 是否已编入索引?

mysql - 在连接两个大表时优化 ORDER BY

Mysql在不同的表查询中多次使用最后插入的id

sql - PostgreSQL 外键约束违反继承

php - 在查询中返回字符串

SQL复杂查询

c# - 如何使用 C# 在 SQL Server 中查找值是否为 NULL