Friday, 17 February 2012

Finding The nth maximum or minimum using sql query


table T(name varchar,marks number)
select t1.name,t1.marks from T t1 where
     n= ( select count(distinct marks) from T t2 where t1.marks <= t2.marks order by marks desc  )

and for finding nth minimum we just need to reverse the where condition in inner query


select t1.name,t1.marks from T t1 where
     n= ( select count(distinct marks) from T t2 where t1.marks >= t2.marks order by marks desc  )

No comments:

Post a Comment