1

我需要编写一个包含子查询的查询,其中将列出部门名称和每个部门在其 job_title 中具有“代表”一词的员工人数,并且该列表必须按部门 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%';
4

3 回答 3

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;

我发现它更容易阅读/解释,但这最终取决于你。

于 2013-03-18T16:17:30.363 回答
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% 正确,但您可以明白这一点。如果没有所有的连接逻辑,就很难完成它。

这应该会返回所有部门名称和员工职位包含代表的员工人数。

于 2013-03-18T16:17:36.070 回答
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

然而,在现实世界中,您编写代码是为了方便,而不仅仅是为了锻炼。您的代码应该便于所有参与软件开发过程的人员阅读、理解和维护。如果这只是一个练习,那么您可以使用第二个查询。但是,如果您必须在实时应用程序中使用查询,则第一个查询中的方法对您周围的每个人都更好。

于 2013-03-18T16:23:41.303 回答