Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello All,
I have a table which stores the percentage of students. I wabt to get the topper list from it(getting highest 3 percentage acquired students).so which query will be better for it.actually i have tried max aand top functions but they are not suitable.max will give only one value and top will give only first 3 records from database.
so how to get highest 3 records.
Posted

SELECT TOP 5...


????
 
Share this answer
 
Try:
SELECT <fields> FROM <tablename> WHERE <condition> LIMIT <startnumber>,<count> ORDER BY <field> ASC


Or (I hadn't noticed SQL2005 didn't support LIMIT):
SELECT Rank, ID, Percent FROM
    ( SELECT Rank = ROW_NUMBER() OVER (ORDER BY Percent), ID
      FROM myTable
    ) i 
WHERE 
    Rank BETWEEN 1 and 5 
ORDER BY 
    Rank
I haven't tested it, but it should work.
 
Share this answer
 
v2
Comments
Nyarost 23-Aug-10 5:17am    
Limit won't work in SQLServer 2005
How about combining TOP with ORDER BY.
Pseudo code:
SQL
SELECT TOP 3 FROM your_table ORDER BY column_to_sort
 
Share this answer
 
You can use Top 3 itself. First you need to sort the table rows using orderby , so the resulting table will be having the highest first, the second highest on second and so on. Now using Top 3 you can select the topmost 3 records.
SELECT TOP 3 * from( Select * from tablename ORDER By percntagefield )


It is not recommended to use the * , you can select the desired fields by mentioning its entity names
 
Share this answer
 
Try This:
SQL
SELECT * FROM your_table t1 WHERE
3>=(SELECT COUNT(DISTINCT t2.column) FROM your_table t2 WHERE t2.column >= t1.column)
 
Share this answer
 
Comments
Christian Graus 27-Aug-10 5:30am    
Reason for my vote of 1
This is a far worse answer than the ones given four days ago.
tarun_j200 27-Aug-10 5:37am    
Hi Christian!! Could you please tell me why you said this is worse answer??
Christian Graus 27-Aug-10 6:26am    
Because it involves a subquery, which hurts performance, and because it is more convoluted than other examples given which will work perfectly well. SELECT TOP 5 FROM your_table ORDER BY column_to_sort was the best possible answer.
tarun_j200 27-Aug-10 6:38am    
I added this query because it is generic to all databases whether its sql server, oracle or mysql.
There is no keyword like Top in oracle and mysql.

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