Click here to Skip to main content
15,880,469 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How we can get any highest value in table.

table:


id salary
1 300
2 350
3 400
4 500
8 200
9 450


XML
<pre lang="css">Eg. get 3rd high salary;
id    salary
3     400

<pre lang="css">Eg. get 2rd high salary;
id    salary
3     450</pre>


etc.



Query in MSSQL
Posted

You have to use ranking functions[^]. Try!

SQL
--get 1. highest salary
SELECT *
FROM(
    SELECT *, ROW_NUMBER() OVER(ORDER BY Salary DESC) As RowNo
    FROM TableName
    ) AS T
WHERE RowNo=1


See past past questions[^] too.
 
Share this answer
 
v3
Comments
Abhinav S 24-Apr-15 3:39am    
5.
Maciej Los 24-Apr-15 3:51am    
Thank you ;)
Abhinav S 24-Apr-15 3:52am    
There are many different solutions for the poster to try now.
how about
SQL
SELECT TOP 3 FROM salaryTable ORDER BY salary DESC


Result:
4 500
9 450
3 400
2 350
1 300
8 200


then use the data record of the result with the appropriate index
0 = highest
1 = second highest
2 = third highest
and so on...

(if you want more than 3 records change the sql query)
 
Share this answer
 
v2
Comments
Abhinav S 24-Apr-15 3:39am    
5.
You can use a CTE as temp table like this, say 3rd highest:
With cte0(id, salary) 
AS
(
select top 3 * from tablename order by salary DESC
)
select top 1 * from cte0

learn more: Common Table Expressions(CTE) in SQL SERVER 2008[^]
 
Share this answer
 
Comments
Abhinav S 24-Apr-15 3:39am    
5.
Peter Leow 25-Apr-15 1:42am    
Thank you, Abhinav.
Try
SQL
SELECT * /*This is the outer query part */
FROM myTable Emp1
WHERE (N-1) = ( /* Subquery starts here */
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)


Here N is the nth maximum you want e.g. 2nd or 3rd maximum salary.

If you are using SQL Server 2012, the answer is slightly easier.
SQL
SELECT * FROM myTable
ORDER BY Salary DESC
OFFSET N ROWS
 
Share this answer
 
v3
Comments
Maciej Los 24-Apr-15 3:51am    
5ed!
Use row number over function, order by salary.
 
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