C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » SQL »

How to get the nth highest value from the database table using SQL


Posted Date: 14 Oct 2009    Resource Type: Code Snippets    Category: SQL
Author: KunalMember Level: Gold    
Rating: 1 out of 5Points: 5



Have you ever faced the problem to get the nth highest record from the table. Here is the query to solve the problem. Say table called customer is defined in following way



CREATE TABLE Employee(
FirstName VARCHAR(10),
Salary INT,
)
INSERT INTO Employee VALUES ('Ted',2300)
INSERT INTO Employee VALUES ('John',4000)
INSERT INTO Employee VALUES ('George',600)
INSERT INTO Employee VALUES ('Mary',1100)
INSERT INTO Employee VALUES ('Sam',1700)
INSERT INTO Employee VALUES ('Doris',600)
INSERT INTO Employee VALUES ('Frank',3800)
INSERT INTO Employee VALUES ('Larry',500)
INSERT INTO Employee VALUES ('Sue',2900)
INSERT INTO Employee VALUES ('Sherry',1100)
INSERT INTO Employee VALUES ('Marty',2300)

use this query

SELECT RANK() OVER (ORDER BY Salary) AS [Rank by Salary],
FirstName,
Salary
FROM Employee
output

Rank by Salary FirstName Salary
-------------------- ---------- -----------
1 Larry 500
2 Doris 600
2 George 600
4 Mary 1100
4 Sherry 1100
6 Sam 1700
7 Ted 2300
7 Marty 2300
9 Sue 2900
10 Frank 3800
11 John 4000





Responses

Author: Kunal    15 Oct 2009Member Level: Gold   Points : 0
I have checked this and getting the same results. Try to run all the insert queries I have put and than check the results


Author: Abhay    15 Oct 2009Member Level: Diamond   Points : 1
Hi kunal,

I checked that once again.I think something was missing while copying so that i returned one result.Now it is approved.


Author: Kunal    15 Oct 2009Member Level: Gold   Points : 0
thanks


Author: seema    16 Oct 2009Member Level: Gold   Points : 1
SELECT * FROM (select COL1,COL2, dense_rank() OVER (order BY COLUMN_TO_SELECT_NTH_VAL) rank from TABLE_NAME) WHERE rank=N;







Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Getting nth highest from the table  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Date Format in SQL SERVER 2005
Previous Resource:

Using Dense_Rank in SQL server 2005

Return to Discussion Resource Index
Post New Resource
Category: SQL


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use