使用下面的脚本,我们将注册表保留为最新的regDate
,并使用以前的注册表填充同一电子邮件的 NULL 值。
但是,如果您有三个或更多用户使用相同的电子邮件,则旧的行将被忽略,我们只是将最近的行与第二个最近的行结合起来:
INSERT INTO Users ([email],[firstName],[lastName],[street],[city],[code],[country],[phone],[regDate])
VALUES ('a@a.com', 'Andrew', null, null, null, null, null, null, '2018-03-09 00:00:00');
INSERT INTO Users ([email],[firstName],[lastName],[street],[city],[code],[country],[phone],[regDate])
VALUES ('a@a.com', 'ANDREEW', 'Lopez', null, 'Santos', null, null, null, '2018-03-08 00:00:00');
INSERT INTO Users ([email],[firstName],[lastName],[street],[city],[code],[country],[phone],[regDate])
VALUES ('b@b.com', 'Bob', 'Wilk', null, null, null, null, null, '2018-03-10 00:00:00');
INSERT INTO Users ([email],[firstName],[lastName],[street],[city],[code],[country],[phone],[regDate])
VALUES ('b@b.com', 'Robert', null, 'Sandiego Street', 'Santos', null, null, '456 123 789', '2018-03-05 00:00:00');
SELECT * FROM Users;
INSERT INTO Users ([email],[firstName],[lastName],[street],[city],[code],[country],[phone],[regDate])
SELECT
u.[email],
ISNULL(u.firstName,old.firstName),
ISNULL(u.lastName,old.lastName),
ISNULL(u.street,old.street),
ISNULL(u.city,old.city),
ISNULL(u.code,old.code),
ISNULL(u.country,old.country),
ISNULL(u.phone,old.phone),
u.regDate
FROM Users u
INNER JOIN Users old ON old.Id = (SELECT TOP 1 Id FROM Users oldMax WHERE oldMax.email = u.email AND oldMax.Id <> u.Id ORDER BY oldMax.regDate DESC)
WHERE u.Id = (SELECT TOP 1 new.Id From Users new WHERE new.email = u.email ORDER BY new.regDate DESC);
DELETE FROM Users WHERE Id NOT IN (SELECT MAX(Id) FROM Users GROUP BY email);
SELECT * FROM Users;
在这里,您是一个工作小提琴。