Tuesday, August 18, 2009

SQL Select Maximun/ Minimun value in table

Nth Maximun
select * from

(select row_number() over(order by sal desc) id, * from emp ) a
where a.id =2 //Where 2 is second Maximum

select * from tblStudent a where &n-1=(select count(*) from tblStudent b where a.mark lt b.mark)
(OR)
select * from tblStudent a where &n=(select count(*) from tblStudent b where a.mark<=b.mark)
Example
select * from tblStudent a where 2=(select count(*) from tblStudent b where a.mark<=b.mark)
//Where 2 is second Maximum

Nth Minimum
select * from
(select row_number() over(order by sal asc) id, * from emp ) a
where a.id =2
//Where 2 is second Minimum

select * from tblStudent a where &n-1=(select count(*) from tblStudent b where a.mark>b.mark)
(OR)
select * from tblStudent a where &n=(select count(*) from tblStudent b where a.mark>=b.mark)
Example
select * from tblStudent a where 2=(select count(*) from tblStudent b where a.mark>=b.mark)
//Where 2 is second Minimum

2nd Maximum
Select max(mark) From tblStudent where mark NOT IN (Select max(mark) From tblStudent)

Select top(1) From tblStudent where mark NOT IN (Select max(mark) From tblStudent) Order By mark desc

Select top(1) From tblStudent where mark IN (Select max(mark) From tblStudent where mark NOT IN (Select max(mark) From tblStudent))

No comments:

Post a Comment