SQL查询关于第二个Max薪水

时间:2014-01-17 10:49:51

标签: sql oracle

我希望从Employee表获得第二高薪。所以请帮我看看。我通过使用以下查询尝试了它。

Select Max(salary) from Employee;

它从薪水栏中获得最高薪水。但我想要第二高薪。

6 个答案:

答案 0 :(得分:2)

 select max(sal) from
 (select sal,dense_rank() over (order by sal desc) dr from emp) where dr=2;
  • 如果薪水如5000,3000,3000,2000 ...... Dense_rank()会给你3000工资的员工

答案 1 :(得分:0)

以下是示例

SELECT *
FROM (
    SELECT column1, 
     row_number() over (order by salary desc) as [rownum]
     From sal_table
 ) t
 WHERE [rownum] = 2

如果有多个行具有相同的薪水,您可以使用dense_rank代替row_number()

答案 2 :(得分:0)

SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )

这给你第二高。

答案 3 :(得分:0)

试试这个

DECLARE @N int
SET @N = 2  -- Change the value here to pick a different salary rank

SELECT Salary
FROM (
    SELECT row_number() OVER (ORDER BY Salary DESC) as SalaryRank, Salary
    FROM Salaries
) as SalaryCTE
WHERE SalaryRank = @N

答案 4 :(得分:0)

不仅是第二名工资,而且你可以通过这个查询获得所有你想要的最高工资(比如第3,第5)。

select salary from(select rownum rn,salary from
(select distinct(salary) from emp order by salary desc)) x where x.rn in (1,2,3);

只需替换(1,2,3)代替(3,5)所需的薪水位置,这样就可以获得第3和第5高薪,如:

select salary from(select rownum rn,salary from
(select distinct(salary) from emp order by salary desc)) x where x.rn in (3,5);

答案 5 :(得分:0)

还有一个:

 SELECT a.salary
   FROM employee a
  WHERE (:n - 1) = (SELECT COUNT(1)
                     FROM employee b
                    WHERE b.salary > a.salary);

只需将n替换为您想要的第n个。