create table #ActiveStatus ( AcctId int, ActiveStatus bit not null, -- 1 = Active 0 = Inactive ActivityDate datetime);goinsert into #ActiveStatus (AcctId, ActiveStatus, ActivityDate)select 1, 1, '2007-11-15' union allselect 1, 0, '2007-11-25' union allselect 1, 1, '2007-12-15' union allselect 2, 1, '2007-10-15' union allselect 2, 0, '2007-11-15' union allselect 3, 1, '2007-08-15' union allselect 3, 0, '2007-09-15' union allselect 3, 1, '2007-09-16' union allselect 3, 0, '2007-09-17' union allselect 3, 1, '2007-11-15' union allselect 4, 1, '2007-11-15';goselect * from #ActiveStatus;godeclare @StartDate datetime, @EndDate datetime, @AcctId int;set @StartDate = '2007-10-01';set @EndDate = '2007-12-31';set @AcctId = 1;with MaxActivity ( AcctId, ActivityDate) as (select AcctId, max(ActivityDate)from #ActiveStatuswhere AcctId = @AcctId and ActivityDate >= @StartDate and ActivityDate < @EndDategroup by AcctId)select a.ActiveStatusfrom #ActiveStatus a inner join MaxActivity ma on (a.AcctId = ma.AcctId and a.ActivityDate = ma.ActivityDate)godrop table #ActiveStatus;go