Monday, 12 March 2018

Find nth highest salary in SQL?

// Create Database
create database LearningPoint92;

//Select Database
 use  LearningPoint92;

//Create table Emp
create table Emp(id int not null,name varchar(12) not null,address varchar(23) not null,salary int not null,primary key(id));

//Retrieve from Emp
select * from emp;

//Insert Data into Emp
insert into Emp(id,name,address,salary)values(101,'suryosnata','pune',35000);
insert intoEmp(id,name,address,salary)values(102,'dipak','vimannagar',45000);
insert into Emp(id,name,address,salary)values(103,'bhargavi','pune',30000);
insert intoEmp(id,name,address,salary)values(104,'pratikshya','nigdi',45000);
insert into Emp(id,name,address,salary)values(105,'prachi','kharadi',95000);
insert into Emp(id,name,address,salary)values(106,'dev','odisha',75000);
insert into Emp(id,name,address,salary)values(107,'bapu','bhadrak',25000);
insert into Emp(id,name,address,salary)values(108,'omkar','akrudi',95000);
insert into Emp(id,name,address,salary)values(109,'kajol','Cuttack',15000);

//Retrieve from Emp
select * from emp;
Output:
101 suryosnata pune 35000
102 dipak  viman nagar 45000
103 bhargavi      pune        30000
104 pratikshya   nigdi        45000
105 prachi kharadi        95000
106 dev         odisha       75000
107 bapu bhadrak       25000
108 omkar akrudi       95000
109 kajol Cuttack      15000

//Retrieve  salary from Emp(descending order)
select  * from Emp order by salary desc;
Output:
105 prachi kharadi        95000
108 omkar akrudi         95000
106 dev         odisha         75000
102 dipak viman nagar 45000
104 pratikshya nigdi        45000
101 suryosnata pune        35000
103 bhargavi  pune        30000
107 bapu bhadrak        25000
109 kajol Cuttack        15000

//Retrieve  highest salary from Emp
 select MAX(salary) from Emp;
Output: 95000

//Retrieve 2nd highest salary from Emp
select MAX(salary) from Emp where salary<(select MAX(salary) from Emp);
 Output:75000

//Retrieve both 1st and 2nd highest salary from Emp
select distinct top 2 salary from Emp order by salary desc;
Output:
95000
75000

//Retrieve 3rd highest salary from Emp
select top 1 salary from (select distinct top 3 salary from Emp order by salary desc) result order by salary;
Output:
45000

//Retrieve 6th highest salary from Emp
 select top 1 salary from (select distinct top 6 salary from Emp order by salary desc) result order by salary;
Output:25000


No comments:

Post a Comment

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...