Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
3.67/5 (3 votes)
See more:
Only using a single query, how we get first, third and fifth highest salary together from a 'salary_table'.
Posted
Comments
Herman<T>.Instance 9-Mar-15 8:28am    
MS SQL server, MySQl, Oracle, SAP/Sybase?
Deepak Tiwari (D'pak) 9-Mar-15 8:48am    
MS SQL Server

easier solution without CTE:
SQL
SELECT Name, Salary FROM
(
   SELECT ROW_NUMBER() OVER (order by salary desc) as rowNr, name, salary
   From tblSalary
) as r
where r.rowNr in (1,3,5)
 
Share this answer
 
Comments
Rajesh waran 9-Mar-15 9:27am    
5*
Deepak Tiwari (D'pak) 9-Mar-15 9:27am    
working fine............thanks
Maddy selva 9-Mar-15 9:31am    
my 5+
W Balboos, GHB 9-Mar-15 10:08am    
Nice. Clean. => Elegent => +5
 
Share this answer
 
Try like this If you are using Sql Server 2008 R2 , It'll work,
And i am considering table name as Table1 and sample column name as Name,Column2,Column3.
SQL
with cte as (select a.Name,a.Column2,a.Column3,MAX(a.Salary) as Max_Salary,ROW_NUMBER() over(order by a.Name) as Rn  from Table  as a group by a.Name,a.Column2,a.Column3 ) select * from cte where Rn in (1,3,5)


Checked and it works,
Hope it will be helpful to you.
 
Share this answer
 
v4
Comments
Herman<T>.Instance 9-Mar-15 9:01am    
why order by a.Name. The key is the Salary the name will show up after that.
Rajesh waran 9-Mar-15 9:26am    
Yes you are right. And your solution looking Good.
SELECT TOP 5 Salary FROM salary_table ORDER BY Salary DESC

Ignore returned records #2 and #4
 
Share this answer
 
v2
Comments
Deepu S Nair 9-Mar-15 9:20am    
?
[no name] 9-Mar-15 9:22am    
Please read the question, look at my solution and vote up instead of down :-)
Deepu S Nair 9-Mar-15 9:24am    
what you mean by "Ignore results 2 and 4"?
[no name] 9-Mar-15 9:27am    
He's asking for the first, third and fifth highest salary. My query returns first, second, third, fourth and fifth highest. So he would just have to ignore (= skip reading) the second and fourth result in order to get just the first, third and fifth.
Deepu S Nair 9-Mar-15 9:31am    
Skip reading?Before arguing just check solution 3.

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