在子查询

时间:2016-04-08 00:45:11

标签: sql-server subquery aggregate-functions

我正在寻找特定查询问题的解决方案。我有一个表Departments和表Employees设计如下:

Departments                      Employees
=====================            ============================
ID | Name                        ID | Name | Surname | DeptID
---------------------            ----------------------------
1  | ADMINISTRATION              1  | X    | Y       | 2
2  | IT                          2  | Z    | Z       | 1
3  | ADVERTISEMENT               3  | O    | O       | 1
                                 4  | A    | B       | 3

我想获得员工人数少于行政管理人员数量的所有部门的清单。 这是我的一个想法,但它不起作用:

select * from Departments as Depts where Depts.ID in
(select Employees.ID from Employees group by Employees.ID
 having count(Employees.ID) < count(case when Depts.Name='ADMINISTRATION' then 1 end));

1 个答案:

答案 0 :(得分:1)

使用GROUP BYHAVING

SELECT
    d.ID, d.Name
FROM Departments d
LEFT JOIN Employees e
    ON e.DeptID = d.ID
GROUP BY d.ID, d.Name
HAVING
    COUNT(e.ID) < (SELECT COUNT(*) FROM Employees WHERE DeptID = 1)