Select users belonging only to particular departments

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

    I know that this question has already been answered, but it was a fun problem to do and I tried to do it in a way that no one else has. Benefits of mine is that you can input any list of strings as long as each value has a comma afterwards and you don't have to worry about checking counts.

    Note: Values must be listed in alphabetic order.

    XML Solution with CROSS APPLY

    select DISTINCT empID
    FROM employe A
    CROSS APPLY
                (
                    SELECT department + ','
                    FROM employe B
                    WHERE A.empID = B.empID
                    ORDER BY department
                    FOR XML PATH ('')
                ) CA(Deps)
    WHERE deps = 'Y,Z,'
    

    Results:

    empID
    ----------
    A103
    

提交回复
热议问题