Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to get maximum and second maximum in single query

Status
Not open for further replies.

sreenath205

Programmer
Dec 9, 2003
17
0
0
IN
How to get maximum and second maximum using a single query
 
select top 2 *
from tbl
order by fld desc


======================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
 
select * from tbl where fld=(select max(fld) from tbl)
union all
select * from tbl where fld=(select max(fld)-1 from tbl)
 
Think you are looking for something more like:

select * from tbl t1 where val = (select max(val) from tbl t2 where t2.fld = t1.fld)
union all
select * from tbl t1 where val = (select max(val) from tbl t2 where t2.fld = t1.fld and val < (select max(val) from tbl t2 where t2.fld = t1.fld))

or

select * from tbl t1 where val in (select top 2 val from tbl t2 where t2.fld = t1.fld order by val desc)

Be careful about duplicate val's


======================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top