如何在本教程的SQL查询中获取部门名称?

时间:2019-06-16 07:08:52

标签: sql

按照有关SQL here的教程进行操作之后,我想查询每个部门的员工人数以及部门名称。

我在该教程中尝试了以下查询:

SELECT count(*), dept_name
FROM employees, departments
WHERE employees.dept_id = departments.dept_id
GROUP BY departments.dept_id

但返回

COUNT(*)    dept_name
2           NULL
2           NULL

代替预期的输出

COUNT(*)    dept_name
2           Accounting
2           Sales

我在这里做什么错了?

2 个答案:

答案 0 :(得分:3)

首先使用JOIN代替WHERE

然后按dept_id分组,以确保您没有重复的姓名,例如2个销售部门或2个同名员工。

SELECT departments.dept_id, dept_name, count(*)
FROM employees
JOIN departments
  ON employees.dept_id = departments.dept_id
GROUP BY departments.dept_id, departments.dept_name

答案 1 :(得分:2)

dept_name而非dept_id分组

SELECT count(*), dept_name
FROM employees, departments
WHERE employees.dept_id = departments.dept_id
GROUP BY departments.dept_name

您最好像join的回答那样使用Juan Carlos Oropeza

SELECT count(*), dept_name
FROM employees JOIN departments ONemployees.dept_id = departments.dept_id
GROUP BY departments.dept_name

enter image description here