使用另一个表中的数据更新sql server表

时间:2010-06-09 11:22:41

标签: sql-server

我有两个基本的SQL Server表:

Customer (ID [pk], AddressLine1, AddressLine2, AddressCity, AddressDistrict, AddressPostalCode)

CustomerAddress(ID [pk], CustomerID [fk], Line1, Line2, City, District, PostalCode)

CustomerAddress包含Customer记录的多个地址。

对于每个客户记录,我想合并最新的CustomerAddress记录,其中最近的记录由最高的CustomerAddress ID值确定。

我目前有以下内容:

UPDATE Customer
SET 
  AddressLine1 = CustomerAddress.Line1,
  AddressPostalCode = CustomerAddress.PostalCode
FROM Customer, CustomerAddress
WHERE 
  Customer.ID = CustomerAddress.CustomerID

有效,但如何确保选择最新(最高ID)的CustomerAddress记录来更新Customer表?

1 个答案:

答案 0 :(得分:2)

这样的事情应该可以解决问题。

UPDATE c
SET c.AddressLine1 = a.Line1
FROM Customer c
    JOIN
    (
        SELECT CustomerID, MAX(ID) AS LatestId
        FROM CustomerAddress
        GROUP BY CustomerID
    ) latest ON c.ID = latest.CustomerID
    JOIN CustomerAddress a ON latest.LatestId = a.ID