2016-10-20 225 views
-1

我表中有许多重复的记录同步,高度simplfied例子是:更新查询重复记录

name, emailaddress, importantid 
John Smith, [email protected], NULL 
John Smith, [email protected], 12345 
John Smith, [email protected], NULL 

在问题出现后,当另一台连接到这一点,它可以连接到一个没有importandd我需要的记录。

我正在寻找更新表,以便对于每个电子邮件地址,它找到第一个importantid不为空,然后使用该ID更新其他记录,因此所有重复的帐户最终有重要的ID。

我该怎么做?

感谢

回答

1

SQL Fiddle Demo

UPDATE a 
SET a.importantid = b.importantid 
FROM test AS a 
JOIN (SELECT emailaddress, max(importantid) as importantid 
     FROM test 
     GROUP BY emailaddress) AS b 
ON a.emailaddress = b.emailaddress; 
+0

我必须仔细检查其是否更新sintaxis。 –

0
UPDATE yourTable t1 
SET importanid =(SELECT max(importantid) 
      FROM yourTable t2 
      WHERE t2.emailaddress = t1.emailaddress AND t1.importantid is null and t2.importantid is not null)