Find nth Highest Salary from Employee Table

How to Find 2nd ,3rd or upto....Nth highest Salary of any employee in SQl

Step 1 Create Table
Create Table emp
(
empName nvarchar(max),
Salary int
)
Step 2 Insert records

1 ) Insert into values emp ('John',2000)
2 ) Insert into values emp ('Kim',5000)
3 ) Insert into values emp ('Walter',1500)
4 ) Insert into values emp ('Obama',3000)
5 ) Insert into values emp ('John Vincet',2500)
6 ) Insert into values emp ('Womek',3500)


Step 3 Query Find the 2nd Highest Salary from emp Table

Select * from emp a Where (2=(Select Count(Distinct b.Salary) from emp b Where b.Salary >= a.Salary))

Step 4 Execute the Step 3 Query


Step 5 For find the nth Highest Salary from emp Table
Select * from emp a Where (n=(Select Distinct(b.Salary) from emp b Where b.Salary >= a.Salary))

Step 6 Check the Ouptut..

Comments

  1. Select * from emp a Where (2=(Select Count(Distinct b.Salary) from emp b Where b.Salary > a.Salary))


    GIVES wrong result.
    It displays Third Highest Salary
    EX. if in SubQuery u written where( 2=(select...)) Then returns 3rd Highest Salary

    where( 1=(select...)) Then returns 2rd Highest Salary

    where( 3=(select...)) Then returns 4rd Highest Salary

    SO U have To modify UR Query to
    Select * from emp1 a Where (0=(Select Count(Distinct b.Salary) from emp1 b Where b.Salary >= a.Salary))

    ReplyDelete
  2. Dear Mahitnahi (BJ)

    Query is giving right answer !

    May be Possible u did mistake while copy paste the code.
    I think u forgot to apply '=' sign in following
    conditions
    Where b.Salary >= a.Salary)

    Check it and Let me Know

    Thanks
    Shubhank Upadhyay

    ReplyDelete

Post a Comment

Popular posts from this blog

String Function in SQL-Substring,Reverse,CharIndex

Difference Between ArrayList and Generic.List C#/VB.Net

How to Use Not IN operator