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
2010-01-29 06:25:19
When the TOP 1 compensation is earned by more than 1 employee, this query will return a wrong result.
Frank Kalis
2010-01-29 08:24:35
If salaries aren't distinct, you can use `SELECT DISTINCT TOP...` instead.
John Feminella
2010-01-29 08:42:43
A:
select salary, employeeid from employees order by salary desc limit 2
Then just get the second row.
James Black
2010-01-29 06:25:59
A:
To use just ANSI SQL, Below is the query:
select max(salary) from emp where salary < (select max(salary) from emp)
Cshah
2010-01-29 06:28:41
it'll run `select max(salary) from emp` for every row, so I don't think it'll be super fast
St.Woland
2010-01-29 06:35:14
+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
2010-01-29 07:03:21
+1
A:
slect max(salary) from emptable where salary < (select max(salary) from emptable);
deepa
2010-06-08 09:38:03
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
2010-06-08 10:41:01