查找SQL Server中所有部门中出现的所有用户?

时间:2013-02-15 10:01:17

标签: sql-server sql-server-2008

我有表Users

我还有表Departments

我在UsersDepartments之间有一张地图表。

我想找到所有部门中显示的所有用户名称 ID

例如,如果有5个部门而Paul只在部门#1中,那么Paul将不在输出列表中。

他会,只有他被列入所有部门(1..5)

我开始使用临时表做一些非常长(很长)的事情,我认为有更好的方法。

我还创建了一个Sql Fiddle

6 个答案:

答案 0 :(得分:1)

试试这个

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)

那会产生

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

sqlfiddle

答案 1 :(得分:1)

这样做的方法不止一种。

您可以要求用户所在的部门数量等于部门总数:

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

您可能要求从所有部门列表中删除用户的部门不会留下任何内容:

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

我确定还有其他人。

答案 2 :(得分:1)

你可以这样做:

select  u.* 
from    Users u
where not exists
(
    select  1 
    from    Departments d 
    where   not exists
    ( 
      select  1 
      from    MapUserstoDepartments m 
      where   d.depId = m.depId
      and     m.userId = u.userId
     )
)

<强> SQL Fiddle

答案 3 :(得分:0)

这是你想要的吗?

Select Tbl.userID , Tbl.username from (Select u.userid , u.username ,  
count(u.userid)  as Count from MapUsersToDepartments m
inner join Users u on m.UserID = u.userID
group by u.userid , u.username)Tbl
where Tbl.Count = (Select count(*) from Departments)

这是小提琴

http://sqlfiddle.com/#!3/5a960/53

答案 4 :(得分:0)

select
  Users.userId,
  count(Departments.depId),
  count(MapUserstoDepartments.userId)

from
  Users
  left join MapUserstoDepartments on MapUserstoDepartments.userId = Users.userId
  left join Departments on Departments.depId = MapUserstoDepartments.depId


group by 
  Users.userId

having
  (SELECT COUNT(*) from Departments) = count(MapUserstoDepartments.userId)

答案 5 :(得分:0)

尝试以下查询。如果这有帮助,请告诉我

 select * from users where userid in
       (select userid from MapUserstoDepartments
       group by userid
        having count(userid) = 5)