Oracle HR 模式。从员工中选择最高工资
Posted
技术标签:
【中文标题】Oracle HR 模式。从员工中选择最高工资【英文标题】:Oracle HR Schema. Selecting of max salary from Employees 【发布时间】:2021-08-07 17:51:24 【问题描述】:我需要从 Oracle HR Schema 中选择城市、城市的最高薪水和薪水最高的员工姓名。 我尝试执行以下代码,但城市名称重复:
select l.city, e.last_name, e.salary from locations l
inner join departments d on l.location_id = d.location_id
inner join employees e on d.department_id = e.department_id
and e.salary = (select max(salary) from employees where department_id = d.department_id)
group by l.city, e.last_name, e.salary
order by e.salary;
我的代码有什么问题? 我已经附上了我需要的结果。Correct SQL result
【问题讨论】:
【参考方案1】:您可以使用DENSE_RANK
分析函数(将返回每个城市最高工资的所有员工):
SELECT city,
last_name,
salary
FROM (
SELECT l.city,
e.last_name,
e.salary,
DENSE_RANK() OVER (
PARTITION BY l.location_id
ORDER BY e.salary DESC
) AS rnk
FROM locations l
INNER JOIN departments d
ON l.location_id = d.location_id
INNER JOIN employees e
ON d.department_id = e.department_id
)
WHERE rnk = 1;
或与KEEP
聚合(这将只返回每个位置的最高薪水和最大姓氏的一名员工):
SELECT MAX(l.city) AS city,
MAX(e.last_name) KEEP ( DENSE_RANK LAST ORDER BY e.salary ) AS last_name,
MAX(e.salary) AS salary
FROM locations l
INNER JOIN departments d
ON l.location_id = d.location_id
INNER JOIN employees e
ON d.department_id = e.department_id
GROUP BY
l.location_id
我的代码有什么问题?
您是在 department_id = d.department_id
上关联,而不是在位置(或城市名称;但是,不要聚合城市名称,因为可能有两个不同的位置同名)。
【讨论】:
以上是关于Oracle HR 模式。从员工中选择最高工资的主要内容,如果未能解决你的问题,请参考以下文章