Problem statement: display max salary based on certain row's id like 2nd rows, 3rd rows, 4th row, 5th row, ... etc.
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);
- CO-RELATED SubQuery: combination of subquery & join
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