如果需要使用子查询,那么以下将实现您正在寻找的内容:
select d.department_id,
d.department_name,
(select count(*)
from employees emp
join jobs j
on j.job_id = emp.employee_job -- I've made some assumptions, here!
where emp.department_id = d.department_id
and j.job_title like '%Representative%') reps
from departments d
order by d.department_id;
但是,就个人而言,我会使用这样的查询:
select d.department_id,
d.department_name,
count(emp.employee_id) reps
from departments d
join employees emp
on emp.department_id = d.department_id
join jobs j
on j.job_id = emp.employee_job -- Same assumption as before!
where j.job_title like '%Representative%'
group by d.department_id,
d.department_name
order by d.department_id;
我发现它更容易阅读/解释,但这最终取决于你。