我需要编写一个包含子查询的查询,其中列出部门名称和每个部门的员工数量,这些部门在其job_title中包含“代表”一词,该列表必须按department_id排序。
我写了这个查询
SELECT d.department_name, emp.employee_id
FROM departments d, employees emp, jobs j
WHERE emp.department_id=d.department_id
AND j.job_title LIKE '%Representative%';
答案 0 :(得分:0)
如果需要使用子查询,那么以下内容将实现您正在寻找的内容:
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;
我觉得阅读/解释更容易,但这最终取决于你。
答案 1 :(得分:0)
您的示例中缺少一些连接逻辑,但这样的事情可能对您有用:
select d.department_name, count(emp.employee_id)
from departments d, employees emp, jobs j
where j.job_title in (select job_title from jobs where job_title like '%Representative%')
group by d.department_name
SQL可能不是100%正确,但你可以看到这一点。没有所有的连接逻辑,很难完成它。
这应该返回所有部门名称和员工职位包含代表的员工人数。
祝你好运保罗。
答案 2 :(得分:0)
您不需要子查询。使用简单的JOIN
。
SELECT d.department_name, COUNT(*) AS cnt
FROM employee e JOIN department d
ON e.department_id = d.department_id
JOIN jobs j ON e.jobid = j.jobid
WHERE j.job_title LIKE '%Representative%'
GROUP BY d.department_name
或者,如果它只是一个练习,我建议使用以下查询:
SELECT d.department_name
, (SELECT COUNT(e.*)
FROM employees e JOIN jobs j ON e.jobid = j.jobid
WHERE e.department_id = d.department_id
AND j.job_title LIKE '%Representative%') AS cnt
FROM departments d
然而,在现实世界中,为方便起见,不仅仅是为了锻炼。您的代码应便于所有参与软件开发过程的人员阅读,理解和维护。如果它只是一个练习,那么你可以使用第二个查询。但是,如果您必须在实时应用程序中使用该查询,则第一个查询中的方法对于您周围的每个人都更好。