我的数据库中有两个表,Department
& DepartmentErrors
。
DepartmentErrors
表包含一个名为' Error
我想在Department
表上运行一个select语句,匹配DepartmentError
中Error
值与数字匹配的该部门的任何相关事件。然后,我想在每个部门的结果集上附加一列,其中包含与该部门ID匹配的行数。错误值出现在部门错误表中。到目前为止,这是我的代码:
SELECT DISTINCT
Department.DeptID,
Name,
Size,
Location,
(
SELECT COUNT(*)
FROM DepartmentErrors
INNER JOIN Departments ON DepartmentErrors.DeptID = Departments.DeptID
WHERE Error = 2
) AS ErrorCount
FROM Departments
INNER JOIN DepartmentErrors ON Departments.DeptID = DepartmentErrors.DeptID
WHERE DepartmentErrors.Error = 2
答案 0 :(得分:1)
试试这个 -
SELECT d.DeptID,
d.Name,
d.Size,
d.Location,
e.ErrorCount
FROM Departments d
JOIN (
SELECT DeptID, ErrorCount = COUNT(*)
FROM DepartmentErrors
WHERE Error = 2
GROUP BY DeptID
) e ON d.DeptID = e.DeptID