一尘不染

获取MySQL表中的第二个最大值

mysql

我有这样定义的员工和薪水表:

"name" (type: VARCHAR)
"salary" (type: INTEGER)

我可以使用什么查询来获得该表中第二高的薪水?


阅读 325

收藏
2020-05-17

共1个答案

一尘不染

这是关系的原因。

Name    Salary
Jim       6
Foo       5
Bar       5
Steve     4

SELECT name, salary
FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees))

Result --> Bar 5, Foo 5

编辑: 我接受了Manoj的第二篇文章,对其进行了调整,并使它更具可读性。对我来说 n-1 不直观;但是,使用我想要的值是2 =
2nd,3 = 3rd等。

/* looking for 2nd highest salary -- notice the '=2' */
SELECT name,salary FROM employees
WHERE salary = (SELECT DISTINCT(salary) FROM employees as e1
WHERE (SELECT COUNT(DISTINCT(salary))=2 FROM employees as e2
WHERE e1.salary <= e2.salary)) ORDER BY name

Result --> Bar 5, Foo 5
2020-05-17