How would I find the second largest salary from the employee table?

Viewed 423029

How would I go about querying for the second largest salary from all employees in my Employee table?

17 Answers

Try something like:

SELECT TOP 1 compensation FROM (
  SELECT TOP 2 compensation FROM employees
  ORDER BY compensation DESC
) AS em ORDER BY compensation ASC

Essentially:

  • Find the top 2 salaries in descending order.
  • Of those 2, find the top salary in ascending order.
  • The selected value is the second-highest salary.

If the salaries aren't distinct, you can use SELECT DISTINCT TOP ... instead.

Maybe you should use DENSE_RANK.

SELECT *
FROM (
       SELECT
         [Salary],
         (DENSE_RANK()
         OVER
         (
           ORDER BY [Salary] DESC)) AS rnk
       FROM [Table1]
       GROUP BY [Num]
     ) AS A
WHERE A.rnk = 2

Try this:

SELECT
    salary,
    employeeid
FROM
    employees
ORDER BY
    salary DESC
LIMIT 2

Then just get the second row.

select distinct(t1.sal) 
from emp t1 
where &n=(select count(distinct(t2.sal)) from emp t2 where t1.sal<=t2.sal);

Output: Enter value for n: if you want 2nd highest ,enter 2; if you want 5,enter n=3

Related