首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不使用任何子查询按部门获取最高薪资

不使用任何子查询按部门获取最高薪资
EN

Stack Overflow用户
提问于 2021-04-26 04:39:41
回答 1查看 53关注 0票数 0

假设我们有两个数据库表- empdept,它们由以下列组成

emp:empid,deptid,工资

dept:deptid,deptname

emp中的deptid列可以与dept列中的deptid列连接。请注意,有些部门没有员工。对于这些情况,dept表中的deptid将不存在于emp表中。我们需要找到每个部门的最高工资。对于没有员工的部门,我们需要从emp表中为他们分配最高的工资。一个要求是不能使用子查询,但允许使用CTE (公共表表达式)。

下面是我构建的查询:

代码语言:javascript
复制
with cte as 
(Select d.deptid, e.salary, row_number() over (partition by d.deptid order by e.salary desc) as rnk,
row_number() over(order by e.salary desc) as salary_rank    
from emp e 
join dept d on e.deptid = dept.deptid),

top_salary as 
(Select d.deptid, e.salary 
from emp e 
join dept d on e.deptid = dept.deptid
order by e.salary desc
limit 1)


(Select d.deptid, cte.salary 
from cte 
join dept d on d.deptid = cte.deptid
where cte.rnk = 1) as t1

UNION 

(Select d.deptid, ts.salary  
from dept d 
left join cte on cte.deptid = d.deptid 
left join top_salary ts on ts.deptid = cte.deptid 
where cte.salary is null
)

但我不确定我是否做得对,尤其是在部门没有员工的情况下。我也不确定我围绕UNION子句编写的2个查询是否被视为子查询。如果它们确实是子查询,那么我是否可以不用任何子查询重写该查询?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-26 12:20:02

我们需要在每个部门找到最高的薪水。对于没有员工的部门,我们需要从emp表中为他们分配最高的工资。

你的尝试似乎过于复杂:

代码语言:javascript
复制
with edmax as (
      select e.deptid, max(e.salary) as max_salary
      from emp
      group by e.deptid
     ),
     emax as (
      select max(e.salary) as max_salary
     )
select d.*, max(edmax.max_salary, emax.max_salary) as max_salary
from dept d left join
     edmax
     on d.deptid = edmax.deptid cross join
     emax;

其基本思想是计算每个部门的最高工资,然后“默认”为总体最高工资。

顺便说一句,只有通过联接才能做到这一点:

代码语言:javascript
复制
select d.deptid, d.name,
       coalesce(max(de.salary), max(d.salary))
from emp e cross join
     dept d left join
     dept de
     on de.deptid = e.deptid
group by d.deptid, d.name;

我不推荐这种方法,但您可能想了解它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67260914

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档