在MS SQL Server中,使用以下数据,如何找到部门10完成(= 1)而没有第11部分的条目的empIds?
deptId empId complete
10 3 1
11 3 0
10 4 1
10 5 1
11 5 0
12 5 1
10 6 1
10 7 1
11 7 0
这应该返回第4和第6版。
答案 0 :(得分:2)
响应:
select distinct empId
from employees e
where e.deptId= 10 and complete = 1
and e.emId not in
(select s_e.empId
from employees s_e
where s_e.deptId = 11
)
查询是具有dept 10 complete(= 1)
的员工列表子查询是具有dept11条目的员工列表。
使用CTE:
WITH employees_excluded_CTE (idEmp)
AS
(
select s_e.empId
from employees s_e
where s_e.deptId = 11
)
select distinct empId
from employees e
where e.deptId= 10 and complete = 1
and e.emId not in
(select s_e.empId
from employees_excluded_CTE
);
GO
答案 1 :(得分:1)
在可能的情况下,在这种情况下,我尝试编写只需要解析一次数据的逻辑。
我可以看到一些方法,而不必使用连接或子查询,这里有几个。确切的形式取决于您的数据的性质(重复等)和/或您拥有或可以创建的索引。
多数通用(全部在HAVING MAX(CASE WHEN THEN) = 0
)
SELECT
empID
FROM
yourTable
WHERE
deptId IN (10,11) -- The only two that matter to your logic
GROUP BY
empID
HAVING
MAX(CASE WHEN deptId = 11 THEN 1
WHEN deptId = 10 AND complete = 0 THEN 1
ELSE 0
END) = 0
更明确,更不通用:
SELECT
empID
FROM
yourTable
WHERE
(deptId = 10 AND completed = 1)
OR
(deptId = 11)
GROUP BY
empID
HAVING
MAX(deptId) = 10