Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Second max value

Author  Topic 

devenoza
Starting Member

14 Posts

Posted - 2011-09-07 : 13:32:09
Hi, could you please help me to find out the second highest value from table? For Ex. if I want to find out second highest salary from Salary table, what should I do? is there a function for this?

Thank you!

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-09-07 : 14:01:09
So this is a classic homework question. Show us what you have tried at least.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

devenoza
Starting Member

14 Posts

Posted - 2011-09-07 : 16:58:53
Sure Tara, I have taken top 2 records from the table and transferred them into temp table and I have deleted the first record from the temp table so the only second record remains. I made it work but I know there must be better way to do this. Any help would be appriciated!
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-09-07 : 17:02:02
Here's how I would do it:

select top 1 salary from (select top 2 salary from table1 order by salary desc) t order by salary asc

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

devenoza
Starting Member

14 Posts

Posted - 2011-09-07 : 17:05:00
Wow! That was quick. Definitely you're SQL Goddess
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-09-07 : 17:12:41
Nah, it's pretty basic stuff, no goddess powers needed here.

You'll get there, just takes lots of time and most importantly practice.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -