0

我想找到一种方法来用其他 2 个更新一个表。这是场景:

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

Info1Tbl & Info2Tbl: complete info

请参阅 SQL Fiddle - http://sqlfiddle.com/#!3/b8b13/1以了解上面创建的表。

基于电话号码,需要EmptyTbl从这两个表中使用最新更新信息进行更新Info1TblInfo2Tbl请帮忙查询。

4

2 回答 2

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 ║
╚════════╩═════════╩═══════╩════════════════╩════════════╝

修改后的 sqlfiddle

于 2013-06-21T21:10:18.430 回答
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

在这里演示

于 2013-06-21T21:11:03.493 回答