2010-06-09 118 views
2

我有兩個基本的SQL Server表:更新SQL Server表的數據從另一個表

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

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

CustomerAddress包含客戶記錄的多個地址。

對於每個客戶記錄,我想合併最近的CustomerAddress記錄,其中最近的CustomerAddress記錄由最高的CustomerAddress ID值確定。

我目前得到了以下內容:

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

其作品,但我怎麼能保證,最近一段時間(最高ID)CustomerAddress記錄選擇更新Customer表?

回答

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 
+0

我認爲在最後一行的第二行有一個錯字,從我的理解中'latest.LatestId'應該是'latest.CustomerID'。我改變它後,它工作正常。我已經修復了你的答案。謝謝。 – 2010-06-09 13:16:04

+0

@David G - 是的,那是一個錯字! – AdaTheDev 2010-06-09 13:20:03

相關問題