Friday, May 18, 2018

How do you display 2nd max, 3rd max, 4th max, ... so on salary from a table? [Co-Related subquery]

Problem statement: display max salary based on certain row's id like 2nd rows, 3rd rows, 4th row, 5th row, ... etc. 
  • CO-RELATED SubQuery: combination of subquery & join
// 2nd max salary:
mysql>SELECT * FROM EMPLOYEE A WHERE 1 = (SELECT COUNT(*) FROM EMP B WHERE A.SALARY < B.SALARY);
output: it will 2nd max salary, because row id begins with 0 & here i'm giving row's id as 1

// 3rd max salary:

mysql>SELECT * FROM EMPLOYEE A WHERE 2 = (SELECT COUNT(*) FROM EMP B WHERE A.SALARY < B.SALARY);

// 4th max salary:

mysql>SELECT * FROM EMPLOYEE A WHERE 3 = (SELECT COUNT(*) FROM EMP B WHERE A.SALARY < B.SALARY);

// Nth max salary:

mysql>SELECT * FROM EMPLOYEE A WHERE N-1 = (SELECT COUNT(*) FROM EMP B WHERE A.SALARY < B.SALARY);
  • Using sub-query:(3rd max salary):
SELECT MIN(EmpSalary) from (
SELECT EmpSalary from Employee ORDER BY EmpSalary DESC LIMIT 3
);

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...