Sushant298
Hello friend
I will show you very simple way to find the nth Highest Salary.
Lets get started :
Step 1 : Create Table Employee
CREATE TABLE [dbo].[Employee]
(
[Eid] [int] NULL,
[EName] [varchar](50) NULL,
[Salary] [money] NULL
)
Step 2 : Insert some DummyData
Insert into Employee(Eid,EName,Salary)Values(1,'Employee1',3000)
Insert into Employee(Eid,EName,Salary)Values(2,'Employee2',5000)
Insert into Employee(Eid,EName,Salary)Values(3,'Employee3',4000)
Insert into Employee(Eid,EName,Salary)Values(4,'Employee4',1000)
Insert into Employee(Eid,EName,Salary)Values(5,'Employee5',2000)
Step 3 : Query to fetch Data
- Here we will create one Maintable and one Auxillary table and correlate the Query with the same table.
Select * from Employee E1 where 2 =
(Select count(*) from Employee E2 where E2.Salary >= E1.Salary)
Explation of Query :
1st record of Maintable(E1) i.e 3000 compared with all records from AuxillaryTable(E2)
3000>=3000 - true - count 1
5000>=3000 - true - count 2
4000>=3000 - true - count 3
1000>=3000 - false - count 3 - Count Remains Same
2000>=3000 - false - count 3 - Count Remains Same
In this case count is 3 so condition wont match, now move to next Record
2nd record of Maintable(E1) i.e 5000 compared with all records from AuxillaryTable(E2)
3000>=5000 - false - count 0
5000>=5000 - true - count 1
4000>=5000 - false - count 1 - Count Remains Same
1000>=5000 - false - count 1 - Count Remains Same
2000>=5000 - false - count 1 - Count Remains Same
In this case count is 1 so condition wont match, now move to next Record
3rd record of Maintable(E1) i.e 4000 compared with all records from AuxillaryTable(E2)
3000>=4000 - false - count 0
5000>=4000 - true - count 1
4000>=4000 - true - count 2
1000>=4000 - false - count 2 - Count Remains Same
2000>=4000 - false - count 2 - Count Remains Same
In this case count is 2 so condition matches as we needed the 2nd highest Salary
Hence the 2nd Higest salary is 4000
If any Query feel free to ask.Thanks