以下是我的专栏:
Employees: Username, Department //a list of every employee and their department
RecentHistory: Employee1, Employee2 //a list of the previous pairings
我需要一个SELECT查询,将所有人与不属于他们部门的其他员工配对,之前他们还没有配对,我希望每个员工在返回的表格中只显示一次。
到目前为止我的查询是:
SELECT t1.Username AS Emplyee1, t2.Username AS Employee2
FROM Employees AS t1 CROSS JOIN Employees as t2
WHERE t1.Department <> t2.Department
EXCEPT
SELECT Employee1, Employee2
FROM RecentHistory
EXCEPT
SELECT Employee2, Employee1
FROM RecentHistory
这使得每个可能尚未完成的配对显示出来但它会多次返回每个员工,我希望每个员工只在结果中出现一次。
如果它有助于此查询返回与CROSS JOIN
查询相同的内容:
SELECT t1.Username, t2.Username
FROM Employees AS t1 JOIN Employees AS t2
ON (t1.Department <> t2.Department)
EXCEPT
SELECT Employee1, Employee2
FROM RecentHistory
EXCEPT
SELECT Employee2, Employee1
FROM RecentHistory
答案 0 :(得分:0)
DECLARE @outTable AS TABLE (Employee1 nvarchar(20), Employee2 nvarchar(20))
DECLARE @users AS TABLE (RowId INT IDENTITY, Username nvarchar(20), Department nvarchar(20))
DECLARE @i int, @cnt int, @username nvarchar(20);
INSERT INTO @users
SELECT Username, Department FROM dbo.Employees
SELECT @i = 1, @cnt = count(*) from @users
WHILE @i <= @cnt
BEGIN
SELECT @username = Username from @users where RowId = @i;
INSERT INTO @outTable
SELECT TOP 1 t1.Username AS Employee1, t2.Username AS Employee2
FROM Employees AS t1 CROSS JOIN Employees as t2
WHERE t1.Department <> t2.Department
AND t1.Username = @username
AND t1.Username not in (select Employee2 from @outTable UNION select Employee1 from @outTable)
AND t2.Username not in (select Employee2 from @outTable UNION select Employee1 from @outTable)
EXCEPT
SELECT Employee1, Employee2
FROM RecentHistory
EXCEPT
SELECT Employee2, Employee1
FROM RecentHistory
SET @i = @i + 1
END
select * from @outTable