你可以做以下UPDATE
:
WITH CTE1 AS
(
SELECT *
FROM Info1Tbl
UNION ALL
SELECT *
FROM Info2Tbl
), CTE2 AS
(
SELECT *,
RN=ROW_NUMBER() OVER(PARTITION BY phone ORDER BY lastupdated DESC)
FROM CTE1
)
UPDATE A
SET A.fname = B.fname,
A.lname = B.lname,
A.address = B.address
FROM EmptyTbl A
INNER JOIN CTE2 B
ON A.phone = B.phone
WHERE B.RN = 1;
SELECT *
FROM EmptyTbl
結果:
╔════════╦═════════╦═══════╦════════════════╦════════════╗
║ CUSTID ║ FNAME ║ LNAME ║ ADDRESS ║ PHONE ║
╠════════╬═════════╬═══════╬════════════════╬════════════╣
║ 001 ║ Tom ║ Suma ║ 999 ABC Street ║ 1234567890 ║
║ 002 ║ Naomy ║ Bath ║ 46 Main Street ║ 1234567891 ║
║ 003 ║ Vanny ║ Smith ║ 1234 Road ║ 1234567892 ║
║ 008 ║ Beth ║ Tan ║ 456 Ave. ║ 1234567893 ║
║ 005 ║ Richard ║ Howie ║ 45 Main Road ║ 1234567894 ║
╚════════╩═════════╩═══════╩════════════════╩════════════╝
而且modified sqlfiddle。
我看過你們的sqlFiddle,我還沒有對你正在嘗試做清楚。 EmptyTbl中的行如何與Info1Tbl和Info2Tbl相關? –
@BillGregg由電話字段 – tkvo