I have the following table with two fields namely a and b as shown below:
create table employe
(
empID varchar(10),
department varchar(10)
);
Solution using where
clause:
select distinct e.empID
from employe e
where exists( select *
from employe
where empID = e.empID
having count(department) = count(case when department in('Y','X','Z') then department end)
and count(distinct department) = 3)
exists
checks if there are records for specific EmpId
that have total count of department
s equal to conditional count of only matching department
s and that it is also equal to the number of department
s provided to the in
clause. Also worth mentioning that here we apply having
clause without the group by
clause, on the whole set, but with already specified, only one empID
.
SQLFiddle
You can achieve this without the correlated subquery, but with the group by
clause:
select e.empId
from employe e
group by e.empID
having count(department) = count(case when department in('Y','X','Z') then department end)
and count(distinct department) = 3
SQLFiddle
You can also use another variation of having
clause for the query above:
having count(case when department not in('Y','X', 'Z') then department end) = 0
and count(distinct case when department in('Y','X','Z') then department end) = 3
SQLFiddle