gpt4 book ai didi

postgresql - 查找每个部门的最高薪水 - 是否有更有效的查询?

转载 作者:行者123 更新时间:2023-11-29 13:10:02 25 4
gpt4 key购买 nike

我有一个有效的查询,但我怀疑我这样做效率低下。是否有更优雅的方法来查找每个部门的最高薪水以及赚取最高薪水的员工?

我正在做一个 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”“工程”“鲍勃”“98756.34”“销售”“丽莎”“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com