SQL-HR Schema,检索部门的Dept.Names,经理和员工

时间:2015-04-01 20:07:24

标签: sql

大家好,并提前感谢您的时间和帮助。 因此,我试图获得部门名单,列出他们的经理姓名和每个部门的员工总数。 到目前为止我的代码看起来像这样:

select d.department_name,e.first_name,e.last_name
from employees e, departments d 
where e.department_id = d.department_id and d.manager_id=e.employee_id
group by d.department_name,e.first_name,e.last_name
order by d.department_name;

生成每个部门的经理列表,但我仍然缺少每个部门的员工数量。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您需要使用COUNT功能。试试这个:

select d.department_name,e.first_name,e.last_name,count(e.employee_id) as `TotalNoOfEmployees`
from employees e JOIN departments d 
ON e.department_id = d.department_id and d.manager_id=e.employee_id
group by d.department_name,e.first_name,e.last_name
order by d.department_name;

也尽量不使用旧的加入表格的方式,即用逗号分隔JOINS。

答案 1 :(得分:0)

经过大量的实验,我得到了它。发布它以防有人可能有一天发现它有用:

select distinct d.department_name,
(select  e.first_name||', '||e.last_name from employees e 
 where d.department_id=e.department_id and 
 d.manager_id=e.employee_id)as "manager_name", 
 ( select count( employee_id ) from employees e
 where d.department_id=e.department_id ) as "total_no_of_employees"   
 from employees e
 join departments d on d.department_id=e.department_id
  order by d.department_name;

答案 2 :(得分:0)

试试这个:

select emp.manager_id, mgr.first_name, mgr.last_name, dept.department_name, count(emp.employee_id)
from hr.employees emp
join hr.employees mgr
on emp.manager_id = mgr.employee_id
join hr.departments dept
on mgr.department_id = dept.department_id
group by emp.manager_id, mgr.first_name, mgr.last_name, dept.department_name
order by department_name