所以我有3个表:管理(...,personID,projectID // personID和projectID可以重复)Project(id,city,...)和Person(id,name,city,...) 我需要输出只仅在同一城市从事项目的人员。 对于任何帮助或想法都将非常有用。
答案 0 :(得分:1)
这是一个简单的查询,其中包含联接,分组依据,具有和count(distinct)以获得所需的结果。
首先,创建并填充示例表(请在您将来的问题中为我们保存此步骤):
DECLARE @Project as table
(
id int,
city varchar(20)
);
DECLARE @Person as table
(
id int,
firstName varchar(10),
lastName varchar(10)
);
DECLARE @Managment as table
(
projectId int,
personId int
);
INSERT INTO @Project (id, city) VALUES
(1, 'Abilene'),
(2, 'Akron'),
(3, 'Albuquerque'),
(4, 'Alexandria'),
(5, 'Allentown');
INSERT INTO @Person (Id, firstName, lastName) VALUES
(1, 'Aaron', 'Carter'),
(2, 'Aaron', 'Eckhart'),
(3, 'Abbie', 'Cornish'),
(4, 'Ace', 'Young'),
(5, 'Adam', 'Brody');
INSERT INTO @Managment (projectId, personId) VALUES
(1, 1),
(1, 2),
(3, 3),
(3, 2),
(3, 5),
(4, 4),
(4, 1),
(5, 5);
查询:
SELECT personId, firstName, lastName, max(city) as city
FROM @Person As pe
JOIN @Managment As m
ON pe.Id = m.personId
JOIN @Project As pr
ON pr.Id = m.projectId
GROUP BY personId, firstName, lastName
HAVING COUNT(DISTINCT city) = 1
(如果您想要两个可以同时使用max
和min
的城市,我将城市的名称作为奖励添加,超过了您不能接受的范围)-请注意{{ 1}}中的count(distinct city)
子句。
结果:
having