在SQL中找到第N个最大的元素

时间:2015-09-05 05:27:33

标签: mysql sql

想知道如何编写SQL函数来查找表中的第N个最大元素,如果没有第N个最大元素,则返回Null。

使用MySQL / MySQL工作台。

顺便说一下,我的问题与第N个最高工资问题不同,因为我有一个额外的要求,如果第N个最大元素不存在则返回Null。任何想法都表示赞赏。

提前谢谢, 林

3 个答案:

答案 0 :(得分:3)

你可以这样做:

SELECT t1.*
FROM (
  SELECT *
  FROM my_table
  ORDER BY value DESC
  LIMIT 1
  OFFSET N -- Set your value for N here, N being 0-based
) t1
RIGHT OUTER JOIN (
  SELECT null -- This will guarantee that you have at least one row
) t2
ON TRUE

答案 1 :(得分:1)

我想不出任何我想要这样做的例子......

SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+

SELECT CASE WHEN COUNT(*) = 9 THEN x.i ELSE NULL END i 
  FROM ints x 
  JOIN ints y 
    ON y.i <= x.i 
 GROUP 
    BY x.i 
 ORDER 
    BY i DESC 
 LIMIT 1;
+------+
| i    |
+------+
|    8 |
+------+

SELECT CASE WHEN COUNT(*) = 11 THEN x.i ELSE NULL END i 
  FROM ints x 
  JOIN ints y 
    ON y.i <= x.i 
 GROUP 
    BY x.i 
 ORDER 
    BY i DESC 
 LIMIT 1;
+------+
| i    |
+------+
| NULL |
+------+

答案 2 :(得分:1)

&#13;
&#13;
SELECT *from Employee_Test_salary

go

with emplsal as(
	SELECT Emp_Sal ,DENSE_RANK() over (order by Emp_Sal desc) as rownumber
	from Employee_Test_salary  
)
select top 1 Emp_Sal from emplsal where emplsal.rownumber =N
&#13;
&#13;
&#13;