tags:

views:

70

answers:

3

Please help me with writing a sql query - I have a table with id, name and marks columns.

If I arrange the table in ascending order of marks, how can I fetch 5 names whose marks are close to a particular name.

+2  A: 

Something like this should do it:

select id, name, marks
from Marks
where name <> 'User1'
order by abs(marks - (select marks from Marks where name = 'User1')) 
limit 5
RedFilter
This is a good solution.
Kangkan
@Orbman: I misread about the order direction, sorry.
OMG Ponies
A: 

Microsoft SQL Server

SELECT TOP 10 column FROM table

PostgreSQL and MySQL

SELECT column FROM table 
LIMIT 10

Oracle

SELECT column FROM table
WHERE ROWNUM >= 3 AND ROWNUM < 10

DB2

SELECT column FROM table
FETCH FIRST 10 ROWS
medopal
The question was clearly tagged as MySQL, and misses the pertinent filter criteria...
OMG Ponies
i noticed the tag, but trying to be informative, i bolded each DB name. I wasn't answering the whole question, just the part where he asked he want to fetch 5 rows. BTW, are you Gizmodos Ponies?
medopal
A: 

Something like this:

select * 
from marks m 
order by abs(m.mark - (select m2.mark from marks m2 where m2.name = "John Doe"))
limit 5; 
sfussenegger