2015-09-05 140 views
0

想知道如何編寫SQL函數來查找表中第N個最大元素,如果沒有第N個最大元素,則返回Null。查找SQL中第N大元素

使用MySQL/MySQL工作臺。

順便說一句,我的問題與第N個最高工資問題不同,因爲我有一個附加要求,如果第N個最大元素不存在,則返回Null。任何想法都表示讚賞。

在此先感謝, 林

+1

[SQL查詢從工資表中查找第N個最高工資]的可能重複(http://stackoverflow.com/questions/3850034/sql-query-to-find-nth-highest-salary-from-a-salary -table) –

+0

@SabyasachiMishra,這是不一樣的。我有一個額外的要求,如果第N個最大的元素不存在,返回Null。任何想法都表示讚賞。 –

+1

你想如何處理同等價值的元素? –

回答

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 
+0

聰明而聰明。 :) –

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 | 
+------+ 
1

SELECT *from Employee_Test_salary 
 

 
go 
 

 
with emplsal as(
 
\t SELECT Emp_Sal ,DENSE_RANK() over (order by Emp_Sal desc) as rownumber 
 
\t from Employee_Test_salary 
 
) 
 
select top 1 Emp_Sal from emplsal where emplsal.rownumber =N