具有相关/嵌套子查询的SELECT语句

时间:2016-01-11 09:50:39

标签: sql sql-server-ce

我的数据库中有两个表,Department& DepartmentErrorsDepartmentErrors表包含一个名为' Error

的列

我想在Department表上运行一个select语句,匹配DepartmentErrorError值与数字匹配的该部门的任何相关事件。然后,我想在每个部门的结果集上附加一列,其中包含与该部门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

1 个答案:

答案 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