在不使用任何子查询的情况下按部门获取最高薪水

Get top salary by department without using any subquery

假设我们有 2 个数据库 tables - empdept,其中包含以下列

emp: empid, deptid, salary

dept: deptid, deptname

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

下面是我构建的查询:

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 个查询是否被视为子查询。如果它们确实是子查询,那么有没有一种方法可以在不使用任何子查询的情况下重写该查询?

We need to find top salary in each department. For departments that don't have any employee, we need to assign them the highest salary from emp table.

您的尝试似乎过于复杂:

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;

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

顺便说一句,您可以仅通过连接来做到这一点:

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;

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