tags:

views:

22

answers:

1

I have two basic SQL Server tables:

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

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

CustomerAddress contains multiple addresses for the Customer record.

For each Customer record I want to merge the most recent CustomerAddress record where most recent is determined by the highest CustomerAddress ID value.

I've currently got the following:

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

which works but how can I ensure that the most recent (highest ID) CustomerAddress record is selected to update the Customer table?

+2  A: 

Something like this should do the trick.

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 
AdaTheDev
I think there's a typo on the second from last line, from my understanding `latest.LatestId` should be `latest.CustomerID`. After I changed that it worked correctly. I've edited your answer with the fix. Thank you.
David G
@David G - ah yes, that was a typo!
AdaTheDev