Monday, 26 March 2018

Find out nth Maximum Salary

Logic
  1. Get salary in decreasing order and give limit n. So, the last salary is required 
  2. Now arrange this is increasing order (ascending order)
  3. Take the first record by using Limit 1, to get the answer
mysql> select * from emp;
+--------+
| salary |
+--------+
|  20000 |
|  50000 |
|  35000 |
|  60000 |
+--------+
Ques - Find 3rd max salary

mysql> select salary from emp order by salary desc limit 3;
+--------+
| salary |
+--------+
|  60000 |
|  50000 |
|  35000 |
+--------+
3 rows in set (0.00 sec)

mysql>  select salary from (select salary from emp order by salary desc limit 3) a order by salary
    -> ;
+--------+
| salary |
+--------+
|  35000 |
|  50000 |
|  60000 |
+--------+
3 rows in set (0.00 sec)

mysql> select salary from (select salary from emp order by salary desc limit 3) a order by salary limit 1;
+--------+
| salary |
+--------+
|  35000 |
+--------+
1 row in set (0.00 sec)
--------------------------------------------------------------------------------------------------------------------------
Ques -  find 2nd min salary = 35000


mysql> select * from emp order by salary limit 2;
asc - first min sal , second min sal
+--------+
| salary |
+--------+
|  20000 |
|  35000 |
+--------+
2 rows in set (0.00 sec)

mysql> select salary from (select salary from emp order by salary limit 2)a order by salary desc ;
+--------+
| salary |
+--------+
|  35000 |
|  20000 |
+--------+
2 rows in set (0.00 sec)

mysql> select salary from (select salary from emp order by salary limit 2)a order by salary desc limit 1 ;
+--------+
| salary |
+--------+
|  35000 |
+--------+
1 row in set (0.00 sec)

No comments:

Post a Comment