nth Highest Salary using window function in sql server
A very common question which you will hear in interviews.
How to find nth highest salary?
Let's do it:
The first step, create a table
create table #Employee(id int, name varchar(15), salary int);
Insert Dummy Data
insert into #Employee(id,name,salary) values(1,'A',100)
insert into #Employee(id,name,salary) values(2,'B',102)
insert into #Employee(id,name,salary) values(3,'C',106)
insert into #Employee(id,name,salary) values(4,'D',102)
insert into #Employee(id,name,salary) values(5,'E',108)
insert into #Employee(id,name,salary) values(6,'F',110)
insert into #Employee(id,name,salary) values(7,'G',117)
How to find nth highest salary?
Let's do it:
The first step, create a table
create table #Employee(id int, name varchar(15), salary int);
Insert Dummy Data
insert into #Employee(id,name,salary) values(1,'A',100)
insert into #Employee(id,name,salary) values(2,'B',102)
insert into #Employee(id,name,salary) values(3,'C',106)
insert into #Employee(id,name,salary) values(4,'D',102)
insert into #Employee(id,name,salary) values(5,'E',108)
insert into #Employee(id,name,salary) values(6,'F',110)
insert into #Employee(id,name,salary) values(7,'G',117)
Let's see what we have in the table
select * from #Employee;
Query to find 3rd Highest Salary using row_number()
select a.id,a.name,a.salary from (
select e.id,e.name,e.salary, row_number() over(order by salary) as rn from #Employee e) as a where rn=3;
Comments
Post a Comment