2015-04-01 195 views
1

大家好,感謝您的時間和幫助。 所以我試圖得到部門名稱的經理姓名和每個部門的僱員總數的名單。 到目前爲止我的代碼看起來是這樣的:SQL-HR架構,檢索部門名稱,每個部門的經理和員工

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; 

產生每個部門經理的名單,但我還是短期每個部門員工的計數。有任何想法嗎?

回答

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; 

也儘量不要使用舊的方式加入表,即逗號分隔連接。

+0

謝謝你的advice.I在說具體點已經嘗試計數功能和運行查詢,但我得到的每一個department.In員工總數在這種情況下,我認爲SQL開發人員計算了滿足d.manager_id = e.employee_id條件的employee_id-manager的編號。 – 2015-04-01 20:28:52

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;