获取MySQL表中的第二高值

编程入门 行业动态 更新时间:2024-10-11 07:31:25
本文介绍了获取MySQL表中的第二高值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have a table of employees and salaries defined that way:

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

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

What query can I use to get the second highest salary in this table?

推荐答案

以下是解决关系的一种方法.

Here's one that accounts for ties.

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等.

I took Manoj's second post, tweaked it, and made it a little more human readable. To me n-1 is not intuitive; however, using the value I want, 2=2nd, 3=3rd, etc. is.

/* 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

更多推荐

获取MySQL表中的第二高值

本文发布于:2023-11-30 08:21:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649337.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:二高   MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!