Saturday 23 November 2013

Finding Second Maximum or Second Minimum in SQL

Bismillahir Rahmanir Raheem

Ok we will be finding the second Maximum and second Minimum salary in this post.

So any Idea how we will go about this problem ?

Think about the problem we have to find the second maximum ,If we can remove the first Maximum and then find Maximum
Then We will get the second Maximum Similarly the case for Second Minimum.

Ok this is the table account

name            salary
A                10000
B                2000
C                500
D                1500
E                1000
F                800


That is how we can solve this question

Select Max(salary) as Second_Maximum
from account
where salary != ( Select Max(salary)
                  from account
                 );

Output will be

Second_Maximum
--------------
2000


Now using same logic we can get Second Minimum

Select Min(salary) as Second_Minimum
from account
where salary != ( Select Min(salary)
                  from account
                   );

Output will  be

Second_Minimum
---------------  
800

No comments:

Post a Comment