Get nth Highest, Lowest Salary of Employee by SQL query

Hello Everybody,

I hope you are enjoying my topics, here this is not just fresh but old, even you like it. I has just shared it previous but now I am sharing it into some brief..I hope you like it..

To Get the highest, lowest salary of employee we use the below query.. 

CREATE TABLE EmployeeSalary (EmpID int identity(1,1), EmpName varchar(100), EmpSalary numeric(18,0))


GO
INSERT INTO EmployeeSalary VALUES('RamLaxman',28000)
INSERT INTO EmployeeSalary VALUES('Satish',32000)
INSERT INTO EmployeeSalary VALUES('Sachin',56000)
INSERT INTO EmployeeSalary VALUES('Rahul',28000)
INSERT INTO EmployeeSalary VALUES('Arvind',68000)
INSERT INTO EmployeeSalary VALUES('Ved',48000)
INSERT INTO EmployeeSalary VALUES('Sunil',58000)


GO
SELECT * FROM EmployeeSalary
GO
--To Get the third Highest Salary
SELECT TOP 1 EmpSalary FROM (SELECT DISTINCT TOP 3 EmpSalary FROM EmployeeSalary ORDER BY EmpSalary DESC) EMPSAL
ORDER  BY EmpSalary ASC
--To Get the second Highest Salary
SELECT TOP 1 EmpSalary FROM (SELECT DISTINCT TOP 2 EmpSalary FROM EmployeeSalary ORDER BY EmpSalary DESC) EMPSAL
ORDER  BY EmpSalary ASC
--the same way you can get the lowest as well
GO
--To Get the third Lowest Salary
SELECT TOP 1  EmpSalary FROM (SELECT DISTINCT TOP 3  EmpSalary FROM EmployeeSalary ORDER BY EmpSalary ASC) EMPSAL
ORDER  BY EmpSalary DESC
--To Get the second Lowest Salary
SELECT TOP 1 EmpSalary FROM (SELECT DISTINCT TOP 2 EmpSalary FROM EmployeeSalary ORDER BY EmpSalary ASC) EMPSAL

ORDER  BY EmpSalary DESC

Cheers,
ved 

Comments