给出以下结构,尝试创建一个显示每个部门名称和每个部门员工人数的过程。
尝试了以下代码,但无法正常工作。
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)
);
答案 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