Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have employee table with Id,Name and salary.

1 E1 10,000
2 E2 20,000
3 E3 30,000
4 E4 20,000
5 E5 50,000

I need third highest all record. What should be my query when there are multiple record with third highest salary. 20,000 is third highest salary and it is twice in database.
Posted
Comments
Kornfeld Eliyahu Peter 20-Oct-15 3:20am    
Look for SQL's ranking functions...

Try:
SQL
SELECT Id, Name, Salary 
FROM (
    SELECT Id, Name, Salary, ROW_NUMBER() OVER (ORDER BY Salary, Id) AS RowNum
    FROM MyTable   
) AS MyDerivedTable
WHERE MyDerivedTable.RowNum = 3
 
Share this answer
 
Comments
Sharma Ravi 20-Oct-15 3:30am    
It is showing only single record as result but result should display both E2 and E4 because both are third highest.
I believe what you are asking is to get the third highest salary and then re-query the employee table and get all the employees with the same third highest salary.

If that is the case, here is one way of doing it:
SQL
select 
	* 
from employee e
inner join (
	select salary
	from employee
	order by salary desc
	offset 3 rows fetch next 1 rows only
) ThirdHighest
	on e.salary = ThirdHighest.salary
;

The main point is, is getting the third highest salary, which can be done in many different ways.
This example uses the OFFSET FETCH Clause, which is a SQL Server 2012+ feature.
 
Share this answer
 
Comments
Sharma Ravi 23-Oct-15 2:44am    
Can you give me some more example to do this?
jaket-cp 23-Oct-15 4:04am    
If you are asking about getting the third highest...
Solution 1 has an example.
You could do something like this
select top 1 salary from (select top 3 salary from employee order by salary desc) order by salary.
Not tested, but you should get logic behind it.
have a look at
http://blog.sqlauthority.com/2007/04/27/sql-server-query-to-retrieve-the-nth-maximum-value/

I am quite sure there are other ways of doing it too.
Do a google search of
"tsql select nth record"
http://lmgtfy.com/?q=tsql+select+nth+record
should get you more examples.

Hope that helps out.

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