我有一个employee表,我正在尝试获取没有活跃员工的部门ID列表。
我的第一次尝试是:
SELECT DISTINCT DivisionID
FROM Employees
WHERE COUNT(IsActive = 0) = 0
GROUP BY DivisionID
但是,即使intellisense认为Count也不允许使用表达式。
所以我尝试了:
SELECT DISTINCT DivisionID
FROM Employees
WHERE SUM(CAST(IsActive AS INT)) = 0
GROUP BY DivisionID
但是随后它抱怨:“除非聚集在HAVING子句或选择列表中包含的子查询中,否则聚集可能不会出现在WHERE子句中,并且所聚集的列是外部引用。”
这似乎应该是直截了当的,不确定是什么问题。
答案 0 :(得分:3)
使用having
,您可以使用条件聚合来过滤您分组的记录
SELECT DivisionID
FROM Employees
GROUP BY DivisionID
HAVING sum(case when IsActive = 1 then 1 else 0 end) = 0
答案 1 :(得分:1)
我怀疑这可以满足您的要求
SELECT DivisionID
FROM Employees
GROUP BY DivisionID
HAVING MAX(IsActive) = 0
答案 2 :(得分:-1)
SELECT DivisionID
from (
SELECT DivisionID, count(*) as tmpcount from Employees WHERE IsActive=0 group by
DivisionID
)
WHERE tmpcount>0