**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
SELECT emp1.departid , emp1.salary
FROM Department emp1
WHERE (
SELECT COUNT(DISTINCT(emp2.salary))
FROM Department emp2
WHERE emp2.salary > emp1.salary and emp1.departid = emp2.departid ) in (0,1) group by emp1.departid , emp1.salary
I have tested this solution in sql server. But i think it will work in ms sql as well.
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
Here is SQLFiddle demo
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).
I believe this is what you want. Please notice that this query is not tested, since I don't have access to a MySQL db atm.
SELECT
d1.id,
d1.salary,
d1.departid
FROM department d
WHERE
d1.id IN
(
SELECT
d2.id
FROM department d2
WHERE
d2.departid = d1.departid
ORDER BY salary DESC
LIMIT 2
)
It's probably not the most efficient query, but it does the job.