Click here to Skip to main content
15,911,711 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
Hi,

How to get second highest salary with out using two select statements please give me the reply

Thank's
Posted
Updated 10-Dec-17 19:49pm
v3
Comments
Member 10629036 26-May-14 6:05am    
With out using Two select statements i want to know the query for second highest salary.
[no name] 26-May-14 6:42am    
Why?
Mandip Grewal 27-May-14 5:18am    
Please check solution number 8 to retrieve second highest salary with one SELECT statement

Try:
SQL
WITH myTableWithRows AS (
    SELECT (ROW_NUMBER() OVER (ORDER BY myTable.Salary DESC)) as row,*
    FROM myTable)
SELECT * FROM myTableWithRows WHERE row = 2
 
Share this answer
 
Comments
Mandip Grewal 27-May-14 4:44am    
If there are two employees who have highest salary then this query will fetch the highest salary of second employee... You have to use DENSE_RANK() function instead of ROW_NUMBER()..
You can retrieve the second highest salary using following two queries..

In first query we have used CTE and DENSE_RANK to retrieve the second highest salary

SQL
WITH myTableWithRows AS (
SELECT (DENSE_RANK() OVER (ORDER BY myTable.Salary DESC)) as row,*
FROM myTable)

SELECT * FROM myTableWithRows WHERE row = 2


In second query, SELF JOIN is used to retrieve the second highest salary and also haven't used two SELECT statements.

SQL
SELECT top 1 t2.Salary 
FROM myTable t1, myTable t2
WHERE t1.Salary > t2.Salary 
ORDER BY t1.Salary DESC, t2.Salary DESC
 
Share this answer
 
v2
SQL
SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )

or
SQL
select MAX(Salary) from Employee
WHERE Salary <> (select MAX(Salary) from Employee )
 
Share this answer
 
try this.. :)


SQL
select top 1 salary from tableName where salary < (select max(salary) from tableName) order by salary desc
 
Share this answer
 
SQL
select max(salary) from emp where salary<(select max(salary) from emp)


Once try it Above Query
By
Srinu.T
 
Share this answer
 
v2
SQL
SELECT
    TOP 1 *
FROM
    (
    SELECT
        TOP 2 *
    FROM
        Employee t
    ORDER BY
        t.Salary DESC
    ) t
ORDER BY
    t.Salary ASC
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900