【发布时间】:2021-07-19 11:44:29
【问题描述】:
假设我们有 2 个数据库表 - emp 和 dept,它们由以下列组成
emp: empid, deptid, 薪水
dept: 部门编号,部门名称
emp 中的 deptid 列可以与dept 中的 deptid 列连接。请注意,某些部门没有任何员工。对于这些情况,dept 表中的 deptid 将不会存在于emp 表中。
我们需要找到每个部门的最高薪水。对于没有任何员工的部门,我们需要为他们分配emp 表中的最高工资。一项要求是我们不能使用子查询,但允许使用 CTE(公用表表达式)。
下面是我构建的查询:
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 子句编写的两个查询是否被视为子查询。如果它们确实是子查询,那么有没有一种方法可以在不使用任何子查询的情况下重写该查询?
【问题讨论】:
-
样本数据和预期结果将帮助您的问题吸引答案。 ps:CTE 是子查询(生成“派生表”),禁止子查询但允许 CTE 是无稽之谈 - 但大概教学人员只是希望看到您使用该技术。
标签: sql common-table-expression window-functions