我想找到一种方法来更新其他2个表。 这是场景:
EmptyTbl: contents missing info (fname, lname, address)
Info1Tbl & Info2Tbl: complete info
请参阅SQL Fiddle - http://sqlfiddle.com/#!3/b8b13/1以获取上表。
根据电话号码,需要从EmptyTbl
&更新Info1Tbl
Info2Tbl
以及来自这两个表的最新更新信息。请帮助查询。
答案 0 :(得分: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 ║
╚════════╩═════════╩═══════╩════════════════╩════════════╝
答案 1 :(得分: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