Select users belonging only to particular departments

后端 未结 12 2244
挽巷
挽巷 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:44

    You can use GROUP BY with having like this. SQL Fiddle

    SELECT empID 
    FROM employe
    GROUP BY empID
    HAVING SUM(CASE WHEN department= 'Y' THEN 1 ELSE 0 END) > 0
    AND SUM(CASE WHEN department= 'Z' THEN 1 ELSE 0 END) > 0
    AND SUM(CASE WHEN department NOT IN('Y','Z') THEN 1 ELSE 0 END) = 0
    

    Without GROUP BY and Having

    SELECT empID 
    FROM employe E1
    WHERE (SELECT COUNT(DISTINCT department) FROM employe E2 WHERE E2.empid = E1.empid and  department IN ('Z','Y')) = 2
    EXCEPT
    SELECT empID 
    FROM employe
    WHERE department NOT IN ('Z','Y')
    

    If you want to use any of the above query with other tables using a join you can use CTE or a derived table like this.

    ;WITH CTE AS 
    (
    
        SELECT empID 
        FROM employe
        GROUP BY empID
        HAVING SUM(CASE WHEN department= 'Y' THEN 1 ELSE 0 END) > 0
        AND SUM(CASE WHEN department= 'Z' THEN 1 ELSE 0 END) > 0
        AND SUM(CASE WHEN department NOT IN('Y','Z') THEN 1 ELSE 0 END) = 0
    )
    SELECT cols from CTE join othertable on col_cte = col_othertable
    

提交回复
热议问题