This is one way to do it. Done only minimal testing, so if it does not seem like it is not giving the right answers, please post sample data that shows the problem (in a way in which someone can copy it and run, like I have in my sample data).-- SAMPLE DATAif object_id('tempdb..#tmp') is not null drop table #tmp;create table #tmp (id int, typeid varchar(2), datestamp datetime);insert into #tmp values ('123','C1','1/1/2010');insert into #tmp values ('123','A1','1/1/2010');insert into #tmp values ('123','A3','1/1/2011');insert into #tmp values ('123',NULL,'10/1/2010');insert into #tmp values ('123',NULL,'11/1/2010');insert into #tmp values ('124',NULL,'10/1/2010');insert into #tmp values ('124',NULL,'1/1/2010');insert into #tmp values ('125',NULL,'1/1/2011');insert into #tmp values ('125','A1','1/1/2010');insert into #tmp values ('125',NULL,'11/1/2010');-- QUERYwith A as(select id,max(datestamp) Dt,max(case when typeid is not null then datestamp end) tDtfrom #tmp group by id)select a.id, t.typeid, a.Dtfrom A inner join #tmp t on t.id = a.id and coalesce(tDt,dt) = t.datestamp;-- CLEANUPdrop table #tmp;