我有一个表1:
First Name Last Name Birthyear Modifieddate
John Doe 1990 2/25/2011
John Doe 1995 3/2/2011
其中最新记录(即出生年份为1995年的行)包含最新的准确信息。
我想插入正确的'最新的生日到另一张桌子。
我写的原始查询是:`
UPDATE TABLE2
SET Birthyear = TABLE1.Birthyear FROM
TABLE 1 JOIN TABLE 2 ON TABLE1.First_name = TABLE2.First_name
AND TABLE1.Last_name = TABLE2.Last_name
但是这会从第一张记录中插入birthyear(1990)。
如何修改查询以便插入正确的"最新的"信息?
答案 0 :(得分:3)
使用cross apply
:
update t2 set birthyear = ca.birthyear
from Table2 t2
cross apply(select top 1 birthyear
from Table1 t1
where t1.firstname = t2.firstname and
t1.lastname = t2.lastname
order by t1.Modifieddate desc) ca
答案 1 :(得分:0)
您可以根据最新的birthyear
获取最新modified_date
,并在另一个表格中更新,如下所示:
;WITH t1
AS (
SELECT first_name
,last_name
,max(birthyear) recent_birthyear
,max(modified_date) last_modified_date
FROM table1
GROUP BY first_name
,last_name
)
UPDATE t2
SET t2.Birthyear = t1.recent_birthyear
FROM TABLE2 t2
JOIN t1 ON t1.First_name = t2.First_name
AND t1.Last_name = t2.Last_name
SELECT *
FROM table2