2015-01-11 62 views
0

編寫SQL查詢以從Employee表獲得第n個最高工資。sql從表中獲得第N個最高工資

+----+--------+ 
| Id | Salary | 
+----+--------+ 
| 1 | 100 | 
| 2 | 200 | 
| 3 | 300 | 
+----+--------+ 

例如,給定上述Employee表,其中n = 2是200。如果沒有第n個最高薪水的第n個最高的薪水,則查詢應該返回null。

我的回答

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT 
BEGIN 
    RETURN (

     # Write your MySQL query statement below. 
    SELECT Salary FROM Employee ORDER BY Salary DESC LIMIT N-1, 1 

); 
END 

錯誤:

Runtime Error Message: Line 6: SyntaxError: near '-1, 1); END' 
Last executed input: {"headers": {"Employee": ["Id", "Salary"]}, "argument": 1, "rows": {"Employee": [[1, 100]]}} 
+0

好像Postgres的你確定這是MySQL的 – Mihai

+0

如何在mysql中做到這一點? @Mihai – BufBills

+0

看這裏http://stackoverflow.com/questions/2875238/passing-limit-as-parameters-to-mysql-sproc – Mihai

回答

0
DELIMITER $ 
CREATE FUNCTION salarynth(n1 INT) 
    RETURNS INT 
    DETERMINISTIC 
    BEGIN 
    DECLARE myvar INT; 
    SELECT 
SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(group_concat(salary order by id),','), ',', n1),',',-1) INTO myvar FROM t; 
    RETURN myvar; 
    END$ 
DELIMITER ; 


SELECT `salarynth`('3'); 

300 
相關問題