2016-10-20 4 views
-1

Ich habe eine Reihe von doppelten Datensätzen in einer Tabelle zu synchronisieren, hoch simplfied Beispiel ist:UPDATE Abfrage duplizierte Datensätze

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

Das Problem kommt später, wenn eine andere Tabelle zu dieser verbunden ist, kann es zu einem verbunden werden von den Aufzeichnungen, die nicht das wichtige I haben, das ich brauche.

Ich bin auf der Suche nach der Tabelle zu aktualisieren, so dass für jede E-Mail-Adresse die erste gefunden wird, wo wichtig ist nicht null und aktualisiert dann die anderen Datensätze mit dieser ID, so dass alle doppelten Konten die wichtige ID haben.

Wie könnte ich das tun?

Dank

Antwort

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

Ich habe für die korrekte Aktualisierung sintaxis überprüfen zu verdoppeln. –

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)