UPDATE查询以同步重复的记录

时间:2016-10-20 14:28:58

标签: sql-server

我在表格中有许多重复记录,高度简化的例子是:

name, emailaddress, importantid
John Smith, john@smith.com, NULL
John Smith, john@smith.com, 12345
John Smith, john@smith.com, NULL

稍后当另一个表加入此表时会出现问题,它可能会连接到其中一个没有我需要的importantid的记录。

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

我怎么能这样做?

由于

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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)
相关问题