Select users belonging only to particular departments

后端 未结 12 2250
挽巷
挽巷 2021-02-18 12:49

I have the following table with two fields namely a and b as shown below:

create table employe
(
    empID varchar(10),
    department varchar(10)
);
         


        
12条回答
  •  感动是毒
    2021-02-18 13:36

    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 departments equal to conditional count of only matching departments and that it is also equal to the number of departments 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

提交回复
热议问题