📜  SQL查询找到第二高的薪水?

📅  最后修改于: 2021-09-09 11:34:59             🧑  作者: Mango

考虑下面的简单表格:

Name     Salary
---------------
abc     100000
bcd     1000000
efg     40000
ghi     500000

如何找到工资第二高的员工。例如,在上表中,“ghi”的工资第二高,为 500000。

以下是查找工资最高的员工的简单查询。

SELECT name, MAX(salary) as salary FROM employee 

我们可以嵌套上面的查询来找到第二大工资。

SELECT name, MAX(salary) AS salary
  FROM employee
 WHERE salary < (SELECT MAX(salary)
                 FROM employee); 

RajnishKrJha 还建议了其他方法。

SELECT name, MAX(salary) AS salary 
FROM employee 
WHERE salary IN
(SELECT salary FROM employee MINUS SELECT MAX(salary) 
FROM employee); 
SELECT name, MAX(salary) AS salary 
FROM employee 
WHERE salary  (SELECT MAX(salary) 
FROM employee);

Arka Poddar建议的一种方式。
在 SQL Server 中使用 Common Table Expression 或CTE ,我们可以找到第二高的薪水:

WITH T AS
(
SELECT *
   DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk
FROM Employees
)
SELECT Name
FROM T
WHERE Rnk=2;

如何找到第三大工资?
很简单,我们可以再做一个嵌套。

SELECT name, MAX(salary) AS salary
  FROM employee
 WHERE salary < (SELECT MAX(salary) 
                 FROM employee
                 WHERE salary < (SELECT MAX(salary)
                 FROM employee)
                ); 

请注意,我们可以使用像 MySQL 中的一般查询来查找第 n 个薪水,而不是嵌套第二、第三等最高薪水:

  • SELECT salary 
    FROM employee 
    ORDER BY salary desc limit n-1,1
    
  • SELECT name, salary
    FROM employee A
    WHERE n-1 = (SELECT count(1) 
                 FROM employee B 
                 WHERE B.salary>A.salary)
    

如果多个员工有相同的工资。
假设你必须找到第四高的薪水

SELECT * FROM employee 
WHERE salary= (SELECT DISTINCT(salary) 
FROM employee ORDER BY salary LIMIT 3,1);

通用查询将是

SELECT * FROM employee 
WHERE salary= (SELECT DISTINCT(salary) 
FROM employee ORDER BY salary LIMIT n-1,1);

此解决方案由 Mohit 提供