子查询问题

时间:2011-05-25 16:25:34

标签: sql sql-server

部门(DepartID,DepName)

员工(名称,DepartID)

我需要的是DepName部门的员工数量。

6 个答案:

答案 0 :(得分:1)

我使用的是outer join而不是子查询。

SELECT d.DepName, COUNT(e.Name)
FROM Department d
LEFT JOIN Employees e ON e.DepartID = d.DepartID
GROUP BY d.DepartID, d.DepName

答案 1 :(得分:1)

SELECT d.DepName, COUNT(e.Name)
    FROM Department d
        LEFT JOIN Employees e
            ON d.DepartID = e.DepartID
    GROUP BY d.DepName

答案 2 :(得分:1)

不需要子查询。

SELECT dep.DepName, COUNT(emp.Name)
FROM DepName dep
    LEFT OUTER JOIN Employees emp ON dep.DepartID = emp.DepartID
GROUP BY dep.DepName

答案 3 :(得分:1)

SELECT COUNT(DISTINCT Name) FROM  
 Department AS d, Employees AS e   
WHERE d.DepartID=e.DepartID AND d.DepName = '$thename'

答案 4 :(得分:1)

要避免使用group by并在查询计划中保存排序操作:

SELECT 
    Department.DepName, 
    (SELECT COUNT(*)
    FROM Employees 
    WHERE Employees.DepartID = Department.DepartID)
FROM 
    Department

答案 5 :(得分:1)

如果您使用的是SQL Server版本 2005 上方,则可以采用另一种方式让员工按部门统计。

SELECT      DPT.DepName
        ,   EMP.EmpCount
FROM        dbo.Department DPT
CROSS APPLY (
                SELECT  COUNT(EMP.DepartId) AS EmpCount
                FROM    dbo.Employees EMP
                WHERE   EMP.DepartId = DPT.DepartId
            ) EMP           
ORDER BY    DPT.DepName

希望有所帮助。

示例测试查询输出:

Output