Here's one way:select yt.id ,yt.status_code ,yt.activity_datefrom ( select id ,'N' as status_code ,max(activity_date) maxDt from [yourTable] where status_code = 'N' group by id ) as dinner join [yourTable] yt on yt.id = d.id and yt.activity_date = d.maxDt and yt.status_code = d.status_code
And here's another assuming you are using 2005 or later:select id ,min(ca.status_code) as status_Code ,min(ca.activity_date) as activity_datefrom [yourTable] ytcross apply ( select top 1 status_code, activity_date from [yourTable] where id = yt.id and status_code = yt.status_code order by activity_date desc ) as cawhere status_code = 'N'group by id
Be One with the OptimizerTG