我有一个有效的问题,但我怀疑我这样做效率低下。有没有一种更优雅的方法来确定每个部门的最高工资以及获得最高工资的员工?
我正在做一个cte来查找每个部门id的最大工资,然后通过匹配工资和部门id将其与员工数据连接起来。我有下面的代码来构建/填充表和最后的查询。

CREATE TABLE employee (
emplid SERIAL PRIMARY KEY,
name VARCHAR NOT NULL,
salary FLOAT NOT NULL,
depid INTEGER
);

INSERT INTO employee (name, salary, depid)
VALUES
('Chris',23456.99,1),
('Bob',98756.34,1),
('Malin',34567.22,2),
('Lisa',34967.73,2),
('Deepak',88582.22,3),
('Chester',99487.41,3);

CREATE TABLE department (
depid SERIAL PRIMARY KEY,
deptname VARCHAR NOT NULL
);

INSERT INTO department (deptname)
VALUES
('Engineering'),
('Sales'),
('Marketing');

--top salary by department
WITH cte AS (
SELECT d.depid, deptname, MAX(salary) AS maxsal
FROM employee e
JOIN department d ON d.depid = e.depid
GROUP BY d.depid, deptname
)
SELECT cte.deptname, e.name, cte.maxsal
FROM cte
JOIN employee e ON cte.depid = e.depid
AND e.salary = cte.maxsal
ORDER BY maxsal DESC;

以下是目标结果:
“市场”“切斯特”“99487.41”
“工程”“Bob”“98756.34”
“销售”“Lisa”“34967.73”

最佳答案

在Postgres中,可以使用distinct on ()运算符解决此问题:

SELECT distinct on (d.depid) d.depid, deptname, e.name, e.salary AS maxsal
FROM employee e
  JOIN department d ON d.depid = e.depid
order by d.depid, e.salary desc;

或者可以使用窗口函数:
select depid, deptname, emp_name, salary
from (
  SELECT d.depid,
         deptname,
         e.name as emp_name,
         e.salary,
         max(e.salary) over (partition by d.depid) AS maxsal
  FROM employee e
    JOIN department d ON d.depid = e.depid
) t
where salary = maxsal;

在线示例:https://rextester.com/MBAF73582

关于postgresql - 查找每个部门的最高薪水-是否有更有效的查询?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56160981/

10-15 21:03