To find the Nth highest salary
Step 1: Create a schema of a table named "Employee" in your database as in the following:
create table Employee
(
ID int identity,
Name varchar(20),
Salary money,
Department varchar(20)
)
Step 2:Insert some values in the table according to the column behaviour like Name and Data Type.
Insert into Employee(Name,Salary,Department)values('Avi',20000,'Finance')
Insert into Employee(Name,Salary,Department)values('Bhar',10000,'Finance')
Insert into Employee(Name,Salary,Department)values('Chait',28000,'IT')
Insert into Employee(Name,Salary,Department)values('Dhar',15000,'Finance')
Insert into Employee(Name,Salary,Department)values('Einstein',39000,'Finance')
Insert into Employee(Name,Salary,Department)values('Fedarer',12000,'Finance')
Insert into Employee(Name,Salary,Department)values('Giri',40000,'IT')
Insert into Employee(Name,Salary,Department)values('Hari',32000,'Finance')
Insert into Employee(Name,Salary,Department)values('Irfa',56000,'IT')
Insert into Employee(Name,Salary,Department)values('Janaki',29000,'Finance')
Select * from Employee
To find the 3 rd highest salary
Query : By using Top
SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP 3 salary
FROM employee
ORDER BY salary DESC
) a
ORDER BY salary
method 2 : By Using MIN
SELECT MIN(Salary)
FROM employee
WHERE Salary IN(SELECT TOP 3 Salary FROM employee ORDER BY Salary DESC)
Method 3 BY using Dense rank
SELECT Salary,Name
FROM
(
SELECT Salary,Name,DENSE_RANK() OVER(ORDER BY Salary DESC) Rno from EMPLOYEE
) tbl
WHERE Rno=3
By using above examples you can find any nth highest salary .You can get any highest value by replace 3 with your value .
Nice work avinash.
ReplyDeleteThank you balakrishna
DeleteGood info dud keep up the good work
ReplyDelete