Menu Close

TSQL – Get Latest Record Related to Another Record

If you would like to get only the latest record that is related to another record (Entity) here is one method of doing that by using a derived table:

In the example below we have a Company table that is related to Activity table. We are going to pull the latest Activity related to each Company.

SELECT Company.Name, la.Subject, la.Date
FROM Company
LEFT JOIN (
SELECT Company.ID AS [CompanyID], Activity.Date, Activity.Subject AS [Subject]
, ROW_NUMBER() OVER ( PARTITION BY Company.ID ORDER BY Activity.Date DESC) as rn

FROM Company
LEFT JOIN Company_Activity ON Company_Activity.Company_ID = Company.ID
LEFT JOIN Activity ON Activity.ID = Company_Activity.Activity_ID
) as la ON la.CompanyID = Company.ID AND la.rn = 1