sql – 使用传递数据自我加入更新查询

我在员工和他的同事数据下面有表格,我想在员工表中更新bucketid,如果有匹配的同事与其他员工.

在这个例子中,

Employee = 101与Employee = 103同事(即c1)匹配,因此两者应该具有相同的bucketid = 1(即两个bucketids的min)

和Employee = 102匹配Employee = 103同事(即c3)所以两者都应该有相同的bucketid,但是这里应该更新为1,因为employee = 102 bucketid刚刚更改为1.我们在此有传递法依赖数据例.

(i.e. a=b and b=c then a=c)

员工表:

EmployeeID  EmployeeName    BucketID
101         williams        1
102         williams        2
103         williams        3
104         williams        4

Employee_Colleague表:

EmployeeID  Colleague
101         c1
101         c2
102         c3
102         c4
103         c1
103         c3
104         c7

我尝试使用此更新查询,

 update a2
 set BucketID = a1.BucketID
 from Employee a1
 inner join Emp_Colleagues c1 on a1.EmployeeID=c1.EmployeeID 
 inner join Employee a2 on a1.EmployeeName=a2.EmployeeName
 inner join Emp_Colleagues c2 on a2.EmployeeID=c2.EmployeeID
 where c1.Colleague=c2.Colleague and a1.BucketID <> a2.BucketID

它返回低于输出.

EmployeeID  EmployeeName    BucketID
101         williams        1
102         williams        1
103         williams        3
104         williams        4

但我想在Employee表中输出如下所示.

EmployeeID  EmployeeName    BucketID
101         williams        1
102         williams        1
103         williams        1
104         williams        4

最佳答案 我不认为你可以在一个更新声明中这样做.但是,您可以使用循环来保持更新,直到没有任何内容可以更新:

declare @updates int = 1
while @updates > 0
begin
    update a2
        set BucketID = a1.BucketID
        from Employee a1
        inner join Emp_Colleagues c1 on a1.EmployeeID=c1.EmployeeID
        inner join Emp_Colleagues c2 on c1.Colleague=c2.Colleague
        inner join Employee a2 on a2.EmployeeID=c2.EmployeeID
        where a1.BucketID < a2.BucketID
    set @updates = @@ROWCOUNT
end
点赞