Select users belonging only to particular departments

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

    This is a Relational Division with no Remainder (RDNR) problem. See this article by Dwain Camps that provides many solution to this kind of problem.

    First Solution

    SQL Fiddle

    SELECT empId
    FROM (
        SELECT
            empID, cc = COUNT(DISTINCT department)
        FROM employe
        WHERE department IN('Y', 'Z')
        GROUP BY empID
    )t
    WHERE
        t.cc = 2
        AND t.cc = (
            SELECT COUNT(*)
            FROM employe
            WHERE empID = t.empID
        )
    

    Second Solution

    SQL Fiddle

    SELECT e.empId
    FROM employe e
    WHERE e.department IN('Y', 'Z')
    GROUP BY e.empID
    HAVING
        COUNT(e.department) = 2
        AND COUNT(e.department) = (SELECT COUNT(*) FROM employe WHERE empID = e.empId)
    

    Without using GROUP BY and HAVING:

    SELECT DISTINCT e.empID
    FROM employe e
    WHERE
        EXISTS(
            SELECT 1 FROM employe WHERE department = 'Z' AND empID = e.empID
        )
        AND EXISTS(     
            SELECT 1 FROM employe WHERE department = 'Y' AND empID = e.empID
        )
        AND NOT EXISTS(
            SELECT 1 FROM employe WHERE department NOT IN('Y', 'Z') AND empID = e.empID
        )
    

提交回复
热议问题