查询4.列出部门名称和每个部门的员工人数(包括承包商)。
select Departments_Name AS "Department", Num_of_employ AS "Number of Employees"
from departments, employee_id
group by Departments_Name, Num_of_employ
order by Departments_Name
offset 0 rows fetch first 12 rows only;
我知道我必须使用聚合函数,但是无论何时执行聚合函数,输出中都会重复“ Accounting”的Departments_Name
我不确定自己在做什么错。有人可以帮我吗?
代码运行
答案 0 :(得分:2)
如果您实际上需要employee_id
表中的信息,则需要使用外键将其加入。也就是说,我看不到您正在使用它。还要使用 proper 连接语法,而不要使用您尝试使用的旧式隐式连接。目前,您将获得每位员工重复的部门行。
然后根据您不想存储Num_of_employ
的方式来决定是否存储group by
。您可能需要对其求和,但是除非每个部门有多个条目,否则这没有任何意义。
select D.Departments_Name as "Department", sum(D.Num_of_employ) as "Number of employees"
from dbo.departments D
-- Do you actually need to join this on? You don't appear to be using it.
-- inner join dbo.employee_id E on E.DepartmentId = D.DepartmentId
group by D.Departments_Name
order by D.Departments_Name
offset 0 rows fetch first 12 rows only;
也许您正在尝试count
工作人员,例如
select D.Departments_Name as "Department", count(*) as "Number of employees"
from dbo.departments D
inner join dbo.employee_id E on E.DepartmentId = D.DepartmentId
group by D.Departments_Name
order by D.Departments_Name
offset 0 rows fetch first 12 rows only;
答案 1 :(得分:0)
我已根据您提出的问题更改了查询,如果您觉得有用,请告诉我
employee_status是诸如合同/永久性之类的数据
select employee_department as "Department", count(*) as "Number of employees",employee_status
from departments
group by Departments_Name,employee_status
order by Departments_Name
offset 0 rows fetch first 12 rows only;