Click here to Skip to main content
15,885,435 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello all,

I had asked a qns in Interview that If i Have a table with 3 fields and 3 records.

S_No Student_Name Student_marks
1 A 90
2 B 78
3 C 95

Now i want to select student name with Top 2 marks with out using TOP function.
Posted
Comments
vivektiwari97701 8-Oct-12 8:07am    
set rowcount 2

select column,column1 from tblEmployeeMaster
Neetesh Agarwal 8-Oct-12 8:59am    
Thanks vivek.
vivektiwari97701 9-Oct-12 4:29am    
u welcome
Neetesh Agarwal 9-Oct-12 23:36pm    
its the sortest method I found..........

SQL
select s_no,Student_name,Student_marks from
(
select Row_number() over(order by Student_marks desc) as a,
s_no,Student_name,Student_marks from tbl
)as temptbl
where a<3


HAppy Coding!
:)
 
Share this answer
 
Comments
Neetesh Agarwal 8-Oct-12 8:59am    
Thanks a lot
Aarti Meswania 8-Oct-12 9:00am    
welcome! :)
Neetesh Agarwal 9-Oct-12 23:37pm    
its working nicely
Aarti Meswania 10-Oct-12 0:32am    
glad to help you! :)
There are a couple options here. One is to use ROWCOUNT, as vivektiwari97701 pointed out. You can specify a ROWCOUNT of 2 and order by Student_marks in descending order like so:
SQL
SET ROWCOUNT 2

SELECT *
FROM tableName
ORDER BY Student_marks DESC

Don't forget to turn ROWCOUNT off afterwards, since it applies to all queries.

Another possibility would be to use the ROW_NUMBER() function in a CTE along like so:
SQL
With cteName AS
( SELECT S_No, Student_Name, Student_marks,
ROW_NUMBER() OVER (order by Student_marks DESC) as RowNumber 
FROM tableName)
select *
from cteName
Where RowNumber Between 1 and 3

The benefit here is that it only applies to this query and it can be changed if you made the numbers parameters. That would allow you to do paging easily. Also note that it is between 1 and 3, which will include 1 but not include 3 (thus records 1 and 2 only).
 
Share this answer
 
Comments
Neetesh Agarwal 8-Oct-12 8:59am    
Thanks for Your answer
Neetesh Agarwal 9-Oct-12 23:30pm    
But its also including 3............
Tim Corey 10-Oct-12 8:00am    
The BETWEEN operator is treated differently in different databases. In SQL server, the 3 is usually not included. If it is being included, change the 3 to a 2.
Neetesh Agarwal 11-Oct-12 6:11am    
Oh may be...........Thanks
I think following code can help you..

SQL
SELECT SNO,STUDENTNAME,MARKS FROM (
         SELECT SNO,STUDENTNAME,MARKS ,ROW_NUMBER()
         OVER(ORDER BY MARKS DESC) ROWNUM 
         FROM STUDENTMARKS
) As A WHERE A.ROWNUM < 3


Thank you
 
Share this answer
 
v2
Comments
Neetesh Agarwal 8-Oct-12 8:59am    
Thanks
damodara naidu betha 8-Oct-12 9:09am    
welcome

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