i am not asking about 2nd highest salary in employee table , i am asking about 2nd highest salary of each employee.
I think a very quick solution could be like this:
SELECT MAX(column) FROM table WHERE column < (SELECT MAX(column) FROM table)
Hope it helps-
inner query will return employees with their highest salary and then from out query those highest salaries will be filtered out so you will get the second highest salary
SELECT MAX(T.salery),T.NAME FROM TABLE T
INNER JOIN (SELECT MAX(salery),NAME FROM TABLE GROUP BY NAME) TT
ON TT.NAME=T.NAME AND TT.SALERY!= T.SALERY
GROUP BY T.NAME;
example
mysql> SELECT * FROM payments;
+----+------------+---------+-------+
| id | date | user_id | value |
+----+------------+---------+-------+
| 1 | 2016-06-22 | 1 | 10 |
| 2 | 2016-06-22 | 3 | 15 |
| 3 | 2016-06-22 | 4 | 20 |
| 4 | 2016-06-23 | 2 | 100 |
| 5 | 2016-06-23 | 1 | 150 |
| 6 | 2016-06-23 | 2 | 340 |
+----+------------+---------+-------+
6 rows in set (0.00 sec)
mysql> select max(value),user_id from payments group by user_id;
+------------+---------+
| max(value) | user_id |
+------------+---------+
| 150 | 1 |
| 340 | 2 |
| 15 | 3 |
| 20 | 4 |
+------------+---------+
4 rows in set (0.00 sec)
mysql> select max(T.value),TT.user_id from payments T inner join (select max(value) as val,user_id from payments group by user_id) TT on T.value!=TT.val and T.user_id=TT.user_id group by T.user_id;;
+--------------+---------+
| max(T.value) | user_id |
+--------------+---------+
| 10 | 1 |
| 100 | 2 |
+--------------+---------+
2 rows in set (0.00 sec)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.