如果给出位置ID,是否可以检索部门数和在该部门工作的员工数

时间:2018-11-19 04:27:52

标签: sql

如果给出位置ID,是否可以检索部门数和在该部门工作的员工数? Location_id列在部门表中。员工和部门共享department_id

此查询无法获得正确的结果:

select 
    count(E.employee_id), count(D.DEPARTMENT_ID)
from 
    employees e   
join 
    departments d on (e.department_id = d.department_id) 
where
    D.LOCATION_ID = 1700;

1 个答案:

答案 0 :(得分:0)

我怀疑您在统计部门时需要distinct

SELECT
    COUNT( E.employee_id )
  , COUNT(DISTINCT d.department_id )
FROM employees e
JOIN departments d ON e.department_id = d.department_id
WHERE d.location_id = 1700;

或者,您需要按部门分组:

SELECT
    COUNT( E.employee_id )
  , d.department_id
FROM employees e
JOIN departments d ON e.department_id = d.department_id
WHERE d.location_id = 1700
GROUP BY d.department_id;