I think this will do it:-------------------------------------------------------------create table variables with sample data to test the statement belowset nocount ondeclare @UserAccount Table(UserAccountID int,UserID int,AccountID int)declare @ActiveLog Table (Record int,EnableDate datetime,DisableDate datetime)insert @UserAccountSelect 1, 1, 2 union allSelect 2, 1, 4 union allSelect 3, 1, 7insert @ActiveLogSelect 1, '1/1/2005', '2/1/2005' union allSelect 2, '11/5/2004', null union allSelect 1, '3/1/2005', null union allSelect 3, '12/3/2004', '2/20/2005'-------------------------------------------------------------Test Select statement against table variables and sample dataSelect ua.AccountID ,agg.EnableDate ,al.disableDateFrom @ActiveLog as alJOIN @UserAccount as ua ON al.Record = ua.UserAccountIDJOIN (--derived table with accountID and latest enabled date Select accountID ,max(EnableDate) EnableDate From @ActiveLog al2 JOIN @UserAccount ua2 ON al2.Record = ua2.UserAccountID Where UserID = 1 Group by AccountID ) as agg --Join to derived table to only include latest --enableDate record for each account ON agg.accountID = ua.accountID and agg.EnableDate = al.EnableDateorder by 1
Be One with the OptimizerTG