获取与条件连接上的所有相应记录匹配的记录

时间:2015-05-18 19:08:22

标签: sql sql-server sql-server-2008-r2

我遇到了一个业务问题,我为以下示例制定了更简单的沟通方式。 假设我有三个表EmployeeProjectEmpWorkProjEmpWorkProj用于链接员工及其工作的项目(或EmployeeProject之间的链接表)。这是表数据的示例: 表:Employee

EmployeeID  EmpName
1           Alex
2           Pete
3           Mike

表:Project

ProjectID   ProjectCity
11          NY
22          LA
33          NY
44          LA

表:EmpWorkProj

EmployeeID  ProjectID
1            11
1            33
1            22
2            11
3            33
3            44

我想要返回的是负责城市'NY'的所有项目的员工。在此示例中,我想返回Alex,因为他是唯一一位处理项目ID 1133的员工。 我真的很感激使用标准sql的解决方案(不能部署递归CTE,动态sql或游标)。感谢。

4 个答案:

答案 0 :(得分:3)

您可以使用group byhaving解决此问题。对于每位员工,计算他们在纽约市作为城市的项目数量。然后,在having子句中,查看是否所有项目:

select ewp.employeeid
from EmpWorkProj ewp join
     Project p
     on ewp.projectid = p.projectid
where p.projectcity = 'NY'
group by ewp.employeeid
having count(*) = (select count(*) from project where projectcity = 'NY')

答案 1 :(得分:3)

这也有效:

declare @e table(EmployeeID int,  EmpName varchar(10))
declare @p table(ProjectID int,  ProjectCity varchar(10))
declare @ep table(EmployeeID int,  ProjectID int)

insert into @e values
(1 ,          'Alex'),
(2 ,          'Pete'),
(3 ,          'Mike')

insert into @p values
(11,          'NY'),
(22,          'LA'),
(33,          'NY'),
(44,          'LA')

insert into @ep values
(1,            11),
(1,            33),
(1,            22),
(2,            11),
(3,            33),
(3,            44)

;with cte as(select ProjectID from @p where ProjectCity = 'NY')
select ep.EmployeeID
from @ep ep
outer apply(select * from cte  except select ProjectID from @ep e where e.EmployeeID = ep.EmployeeID) o
group by ep.EmployeeID
having MAX(o.ProjectID) is null

答案 2 :(得分:2)

所以我正在寻找的解决方案就是这个,感谢Giorgi和Gordon帮助我看到它

SELECT E.EmpName
FROM Employees e 
WHERE NOT EXISTS (SELECT ProjectID 
                  FROM dbo.Project p
                  WHERE p.ProjectCity='NY'
                  EXCEPT 
                  SELECT ProjectID
                  FROM dbo.EmpWorkProj ep
                  WHERE ep.EmployeeID= e.EmployeeID);

答案 3 :(得分:-1)

  

SELECT e.EmpName FROM Employee e, EmpWorkProj ewp,Project p WHERE ewp.ProjectID=p.ProjectID and p.ProjectCity='NY' and ewp.EmployeeID=e.EmployeeID;