Monday, 14 April 2014

How to Calculate the first and second heighest salary or nth heighest salary

ust Run Following script and find the 1st and 2nd heighest Salray and /or nth heighest Salary

-- Dumping structure for table employee.employee
-- Create by Sairam Rajulapti
DROP TABLE IF EXISTS `employee`;
CREATE TABLE IF NOT EXISTS `employee` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(100) DEFAULT NULL,
`Sal` decimal(10,2) DEFAULT NULL,
`City` char(3) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;

-- Dumping data for table employee.employee: ~5 rows (approximately)
DELETE FROM `employee`;
/*!40000 ALTER TABLE `employee` DISABLE KEYS */;
INSERT INTO `employee` (`ID`, `Name`, `Sal`, `City`) VALUES
(1, 'Ramesh', 20000.00, 'BLR'),
(2, 'Sunil', 24000.00, 'DEL'),
(3, 'Sreeja', 21000.00, 'DEL'),
(4, 'Pavan', 23500.00, 'DEL'),
(5, 'Maya', 24000.00, 'MUM');




select max(emp1.Sal) 1stHeightSal,max(emp2.sal) 2ndHeights from employee emp1 ,
employee emp2
where emp1.Sal in (select max(emp.Sal) from employee emp)
and emp2.sal < emp1.sal



--Nth Heghest Salary


-- for nth heighest take n-1 insted of n (if u want 3rd heghest take n=2 
-- if u want 1st heighest thke n=0
select *from employee emp where 
emp.Sal = (select emp2.Sal from employee emp2 group by emp2.Sal order by emp2.Sal desc limit 2,1 )

No comments:

Post a Comment