[英]How my simple sub-query work when a aggregate function and a Group by clause is used?
我有作业问题,对不起,我对此很菜鸟。
我有一个员工表。 我想要一个查询来查找其部门中薪水最高的员工的姓名
我已经写了:
Select emp_name
from employee
where salary=any(select max(salary) from employee group by dept_no)
表名:员工
emp_name salary Dept_no
e1 1000 10
e2 2000 10
e3 2000 20
e4 3000 20
output 应该是:
e2
e4
但这是错误的,有人可以告诉我为什么吗?
您的代码缺少部门的链接,并且仅为薪水设置条件。
您必须将子查询加入到表中:
Select e.emp_name
from employee e inner join(
select dept_no, max(salary) salary
from employee
group by dept_no
) t on t.dept_no = e.dept_no and t.salary = e.salary
或者不存在:
Select e.emp_name
from employee e
where not exists(
select 1 from employee
where dept_no = e.dept_no and salary > e.salary
)
你的问题是部门之间没有联系。 因此,B 部门的某人可能获得 A 部门某人的最高薪水——但可能不是该部门中收入最高的人。
对于这种方法,我建议在子查询中使用相关子句,而不是GROUP BY
:
select e.emp_name
from employee e
where e.salary = (select max(e2.salary)
from employee e2
where e2.dept_no = e.dept_no
------------------------^ correlation clause
);
注意表别名和限定列名的使用。 在编写查询时,您应该始终限定所有表引用——它确保查询执行您想要的操作,并使查询对其他人更容易理解。
如果绩效是一个问题,则使用employee(dept_no, salary)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.