如何返回每个部门的名称和每个部门的员工人数

时间:2020-06-03 14:45:09

标签: sql-server tsql join group-by count

给出以下结构,尝试创建一个显示每个部门名称和每个部门员工人数的过程。

尝试了以下代码,但无法正常工作。

CREATE PROCEDURE SelectDepartmentNameandEmployee
AS
SELECT name
FROM Department
JOIN Employees as e
        on d.departmentID = e.departmentID

表结构

[Department]
(
    [departmentID] INT IDENTITY (1, 1) NOT NULL PRIMARY KEY,
    [name] VARCHAR(50) NOT NULL,
    [costCentreID] INT FOREIGN KEY REFERENCES CostCentre(costCentreID)
);



[Employees]
(
    [employeeNo] INT IDENTITY (1, 1) NOT NULL PRIMARY KEY,
    [lastName] VARCHAR(50) NOT NULL,
    [firstName] VARCHAR(50) NOT NULL,
    [gender] CHAR NOT NULL,
    [IDNumber] VARCHAR(20) NOT NULL,
    [salaryLevelID] INT,
    [departmentID] INT FOREIGN KEY REFERENCES Department(departmentID)
);

1 个答案:

答案 0 :(得分:1)

这是一个简单的聚合查询。您的失败是因为:

  • 它缺少GROUP BY子句
  • 在查询中未定义
  • 表别名d

考虑:

SELECT d.name, COUNT(*) no_employees
FROM Department d
INNER JOIN Employees as e ON d.departmentID = e.departmentID
GROUP BY d.departmentID, d.name

如果您还想显示没有员工的部门,那么:

SELECT d.name, COUNT(e.departmentID) no_employees
FROM Department d
LEFT JOIN Employees as e ON d.departmentID = e.departmentID
GROUP BY d.departmentID, d.name