**Department table name** **following with fields name** id , empid ,salary ,departid ,statushow to get the top two highest salaries from each department with single query in mysql
Try
What it does it generates in inner select a rank for each employee in each department based on the salary. Then in outer select it filters out all rows that have rank more than 2 (top two).
SELECT id, empid, salary, departid, status
FROM
(
SELECT id, empid, salary, departid, status,
@n := IF(@g = departid, @n + 1, 1) rownum,
@g := departid
FROM table1
ORDER BY departid, salary DESC
) q
WHERE q.rownum <= 2
What it does it generates in inner select a rank for each employee in each department based on the salary. Then in outer select it filters out all rows that have rank more than 2 (top two).
0 comments:
Post a Comment