SQL server select distinct rows using most recent value only

One way

select t1.* from (select ForeignKeyId,AttributeName, max(Created) AS MaxCreated
from  YourTable
group by ForeignKeyId,AttributeName) t2
join YourTable t1 on t2.ForeignKeyId = t1.ForeignKeyId
and t2.AttributeName = t1.AttributeName
and t2.MaxCreated = t1.Created

See also Including an Aggregated Column’s Related Values for 5 different ways to do this kind of query

Leave a Comment