我有一个部门表和员工表:
部门:
deptId deptName
0 dept1
1 dept2
2 dept3
3 dept4
员工:
deptId name type
0 aaa 100
0 bbb 200
0 ccc 300
1 ddd 100
1 eee 300
2 fff 200
2 ggg 300
3 hhh 300
因此,每个部门都有多名员工。我该如何检索所有没有100和200型员工的部门
因此,如果我运行查询,我应该得到部门1、2和3,因为拥有这两种类型的雇员的唯一部门是部门0
谢谢
答案 0 :(得分:3)
一种方法使用not exists
:
select d.*
from department d
where not exists (select 1
from employee e
where e.deptid = d.deptid and e.type = 100
) or
not exists (select 1
from employee e
where e.deptid = d.deptid and e.type = 200
) ;
如果您想要求部门至少有一名员工,我可能会进行汇总:
select e.deptid
from employee e
group by e.deptid
having count(distinct case when e.type in (100, 200) then e.type end) < 2;
答案 1 :(得分:2)
具有一个相关的子查询,该查询返回特定类型的不同类型100和200的数量。
select *
from department d
where (select count(distinct type)
from employee e
where type in (100, 200)
and e.deptid = d.deptid
group by deptid) < 2
或者用LEFT JOIN
做GROUP BY
:
select d.deptId, d.deptName
from department d
left join employee e
on e.deptid = d.deptid
group by d.deptId, d.deptName
having count(case when e.type = 100 then 1 end) = 0
or count(case when e.type = 200 then 1 end) = 0