2013-06-21 61 views
0

我想找到一種方法來更新與其他2表。 下面是這種情況:更新SQL記錄與其他2個表

EmptyTbl: contents missing info (fname, lname, address) 

Info1Tbl & Info2Tbl: complete info 

請參閱SQL小提琴 - http://sqlfiddle.com/#!3/b8b13/1用於創建上面的表。

基礎上的電話號碼,並需要從Info1Tbl & Info2Tbl與這2臺最新更新信息更新EmptyTbl。請幫助查詢。

+0

我看過你們的sqlFiddle,我還沒有對你正在嘗試做清楚。 EmptyTbl中的行如何與Info1Tbl和Info2Tbl相關? –

+0

@BillGregg由電話字段 – tkvo

回答

2

試試這個

;with cte as 
(
    select * from info1tbl 
    union all 
    select * from info2tbl 
), cte2 as 
(
    select *, row_number() 
    over (partition by phone order by lastupdated desc) rn 
    from cte 
) 
--select * from cte2 where rn = 1 
update e 
set e.fname = cte2.fname, 
e.lname = cte2.lname, 
e.address = cte2.address 
from emptytbl e 
inner join cte2 on e.phone = cte2.phone 
where rn = 1 

DEMO HERE

+0

非常感謝@rs – tkvo

6

你可以做以下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

+0

真棒,謝謝。 – tkvo