views:

551

answers:

6

how to find out second maximum salary from all employee in employee table ? please give me sql query.

+2  A: 

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.
John Feminella
When the TOP 1 compensation is earned by more than 1 employee, this query will return a wrong result.
Frank Kalis
If salaries aren't distinct, you can use `SELECT DISTINCT TOP...` instead.
John Feminella
A: 

select salary, employeeid from employees order by salary desc limit 2

Then just get the second row.

James Black
A: 

To use just ANSI SQL, Below is the query:

select max(salary) from emp where salary < (select max(salary) from emp)

Cshah
it'll run `select max(salary) from emp` for every row, so I don't think it'll be super fast
St.Woland
+1  A: 

May be you should use 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
Sandy
Replace RANK() with DENSE_RANK() and it works.
Frank Kalis
yes Frank, you're right
Sandy
I'v changed query accordingly
Sandy
+1  A: 

slect max(salary) from emptable where salary < (select max(salary) from emptable);

deepa
A: 

Depends on the version, you can use many methods Refer this http://beyondrelational.com/blogs/madhivanan/archive/2007/08/27/find-nth-maximum-value.aspx

Madhivanan