Wednesday 27 May 2015

mysql query To get the top two salary from each department

**Department table name** 
**following with fields name**

 id , empid ,salary ,departid ,status

how to get the top two highest salaries from each department with single query in mysql
Try
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