我有
employees table(id,f_name,l_name,salary,dept_id,manager_id)
departments table(id,dept_name,manager_id)
我想在单个表格中显示dept_name
其manager_id
、经理l_name
和在各自经理下工作的员工人数。
我有
employees table(id,f_name,l_name,salary,dept_id,manager_id)
departments table(id,dept_name,manager_id)
我想在单个表格中显示dept_name
其manager_id
、经理l_name
和在各自经理下工作的员工人数。
尝试这个:
SELECT dept.dept_name, dept.manager_id, emp.l_name, emp_count.empcount
FROM departments AS dept
INNER JOIN (SELECT COUNT(*) AS empcount, manager_id FROM employees GROUP BY manager_id) AS emp_count ON dept.manager_id = emp_count.manager_id
INNER JOIN employees AS emp ON dept.manager_id = emp.id
或这个:
SELECT dept.dept_name, dept.manager_id, emp.l_name, emp_count.empcount
FROM departments AS dept
INNER JOIN (SELECT COUNT(*) AS empcount, dept_id FROM employees GROUP BY manager_id) AS emp_count ON dept.dept_id = emp_count.dept_id
INNER JOIN employees AS emp ON dept.manager_id = emp.id
第一个是引用manager_id,第二个是引用dept_id。两者中的任何一个都可以得到相同的结果。我通过为员工人数创建一个子查询并将其链接到部门来实现这一点。
你可以通过一个简单的查询来做到这一点,但是你应该删除employees表中的manager_id,只使用员工记录id作为标识符。
Select dept.dept_name, dept.manager_id, (select e.l_name from employees as e where e.id = dept.manager_id), count(select em.id from employees as em where dept.id = em.dept_id) FROM departments as dept
但是,这应该可以工作,您没有提供您正在使用的特定数据库。如果您更新您的问题或告诉什么数据库,如果它不起作用,我可以编辑该数据库。
correlated subquery
您可以通过计数来实现这一点。休息你可以选择使用加入。这可能会帮助你
SELECT D.dept_name,
D.manager_id,
E.l_name,
(SELECT COUNT(*)
FROM employees
WHERE manager_id=D.manager_id) AS numberOfEmployees
FROM departments D INNER JOIN employees E ON D.manager_id=E.id
检查这个
select d.deptname, d.managerid, e.fname, (select COUNT(*)
from employees
where managerid = d.managerid and
managerid <> id and
depid = d.id
group by managerid) NoofEmps
from departments d join employees e on d.managerid = e.id
字段名称可能与您提到的不完全相同。
这是您可以考虑的另一种解决方案
SELECT D.dept_name as [Department Name],
E.manager_id as [Manager ID],
E.l_name as [Last Name],
(SELECT COUNT(*) FROM employees EM WHERE EM.manager_id = E.id) as [Employee Count]
FROM departments D
INNER JOIN employees E on D.manager_id = E.manager_id