我有
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
以及在单个表格中在各自经理下工作的员工数量。
答案 0 :(得分:2)
试试这个:
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。从两者中可以得到相同的结果。我通过为员工数量创建子查询并将其链接到部门来实现这一目标。
答案 1 :(得分:0)
您可以使用简单查询执行此操作,但是,您应该删除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
但这应该有效,您没有提供您正在使用的特定数据库。如果您更新了问题或告诉了什么数据库,我可以编辑该数据库,如果它不起作用。
答案 2 :(得分:0)
检查
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
字段名称可能与您提到的不完全相同。
答案 3 :(得分:0)
您可以通过此correlated subquery
来获取计数。休息你可以选择使用join。这可能会对你有所帮助
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
答案 4 :(得分:-1)
这是您可以考虑的另一种解决方案
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