来自ID的经理姓名

时间:2015-10-21 20:04:10

标签: mysql sql

我已经能够获取经理ID了,但我需要能够获取那些目前卡在那里的三位经理的名字。

select d.manager_id, count(employee_id)
from hr.departments d 
inner join hr.employees e on d.department_id = e.department_id
group by d.manager_id
having count(employee_id) > 5

当我尝试

select d.manager_id, e.first_name, e.last_name, count(employee_id)
from hr.departments d 
inner join hr.employees e on d.department_id = e.department_id
group by d.manager_id, e.first_name, e.last_name
having count(employee_id) >5

我得到空白结果

3 个答案:

答案 0 :(得分:0)

您也必须在joinemployee_id

select d.manager_id, e1.first_name, e1.last_name, count(e.employee_id)
from hr.departments d 
inner join hr.employees e on d.department_id = e.department_id  
inner join hr.employees e1 on d.manager_id = e1.employee_id
group by d.manager_id, e.first_name, e.last_name
having count(e.employee_id) > 5

答案 1 :(得分:0)

inner join hr.employees e on d.department_id = e.department_id
group by d.manager_id, e.first_name, e.last_name

您需要与员工进行另一次联接以获取经理姓名。

select name.first_name, name.last_name,
...
inner join hr.employees name on d.manager_id = name.employee_id

如果您想跳过额外的加入,

select d.manager_id,
       max(case when d.manager_id = e.employee_id then e.first_name end) first_name,
       max(case when d.manager_id = e.employee_id then e.last_name end) last_name,
       count(*)
from   department d
join   employee e on d.department_id = e.department_id
group by d.manager_id having count(*) > 5
;

答案 2 :(得分:0)

问题在于加入。您是否尝试过使用子查询?像

这样的东西
select d.manager_id, e.first_name, e.last_name, count(employee_id)
from hr.departments d 
     inner join hr.employees e on d.department_id = e.department_id
     INNER JOIN (select d.manager_id, 
                 from hr.departments d 
                    inner join hr.employees e on d.department_id = e.department_id
      group by d.manager_id
       having count(employee_id) > 5) as m on d.manager_id = m.manager_id
group by d.manager_id, e.first_name, e.last_name