1. 程式人生 > >sql 面試題 函式 求工資第n多的工資

sql 面試題 函式 求工資第n多的工資

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  RETURN (
select e1.Salary from 
    (select distinct Salary fromEmployee) e1
where 
( 
select count(*) from 
    (select distinct Salary from Employee) e2 
where e2.Salary>e1.Salary)=N-1
);
END
select count(*) from 
    (select distinct
Salary from Employee) e2 where e2.Salary>e1.Salary)

相當於 遍歷e1裡的所有的salary
然後列出e2裡大於e1中每一個salary的所有記錄
當N-1=0時 e1.salary是最大值
當N-1=1時 e1.salary是第二大值
。。。。。。

自行腦補測試