**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
**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
我已经在 sql server 中测试了这个解决方案。但我认为它也适用于 ms sql。
尝试
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
这是SQLFiddle演示
它在内部生成的内容根据薪水为每个部门中的每个员工选择一个等级。然后在外部选择中过滤掉所有排名超过 2 的行(前两个)。
我相信这就是你想要的。请注意,此查询未经测试,因为我无权访问 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
)
这可能不是最有效的查询,但它可以完成工作。