简体   繁体   中英

How my simple sub-query work when a aggregate function and a Group by clause is used?

I have homework problem sorry I am very noob in this.

I have an Employee table. I want a Query to find the Name of an employee drawing highest salary in their departments

I have written:

Select emp_name 
from employee 
where salary=any(select max(salary) from employee group by dept_no)

[在此处输入图像描述]

Table Name: employee

emp_name  salary   Dept_no
e1         1000     10
e2         2000     10
e3         2000     20
e4         3000     20

output should be:

e2 
e4

but it is wrong as can someone tell me why?

Your code is missing the link of the departments and sets the condition only for salaries.
You must join your subquery to the table:

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

Or with NOT EXISTS:

Select e.emp_name 
from employee e 
where not exists(
  select 1 from employee
  where dept_no = e.dept_no and salary > e.salary
) 

Your issue that that there is no connection between the departments. So, someone in Department B might earn the maximum salary of someone in Department A -- but might not be the highest earner in that department.

For this approach, I would recommend a correlation clause in the subquery, rather than 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
                 );

Note the use of table aliases and qualified column names. You should always qualify all table references when writing queries -- it ensures that the query does what you intend and it makes the query more understandable for others.

If performance is an issue, then use employee(dept_no, salary) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM