Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all users which appears in ALL departments in SQL server?

I have Table Users

I also have Table Departments

And I have a map table between Users and Departments.

I want to find all users name and Id which appears in all departments.

for example if there's 5 departments and Paul is only in department #1 , so Paul will not be in the output list.

He would , only if he is listed in all departments (1..5)

I started doing something which is very long (readly long) using temp table and I assume there is a better way.

I also create a Sql Fiddle.

like image 446
Royi Namir Avatar asked Dec 05 '25 08:12

Royi Namir


2 Answers

There's more than one way of doing this.

You could require that the number of departments that the user is in equals the total number of departments:

SELECT
    * 
FROM
    Users
    INNER JOIN 
    (
        SELECT userId, COUNT(*) c FROM MapUserstoDepartments
        GROUP BY userId
        HAVING COUNT(*) = (SELECT COUNT(*) FROM Departments)
    ) UsersInAllDepartments
    ON Users.userId = UsersInAllDepartments.userId

You could require that removing the user's departments from the list of all departments leaves nothing:

SELECT * 
FROM Users
WHERE NOT EXISTS 
  (
    SELECT depId FROM Departments
    EXCEPT
    SELECT depId FROM MapUserstoDepartments WHERE userId = Users.userId
  )

I'm sure there are others.

like image 190
AakashM Avatar answered Dec 07 '25 23:12

AakashM


Try this

SELECT u.userId, u.UserName 
FROM MapUserstoDepartments m INNER JOIN
     Users u ON u.userId = m.userId
GROUP BY u.userId, u.UserName 
HAVING COUNT(m.depId) = (SELECT COUNT(*) FROM Departments)

That will produce

| USERID | USERNAME |
---------------------
|    100 |     John |

And sqlfiddle

like image 21
peterm Avatar answered Dec 07 '25 22:12

peterm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!