SQL Select Distinct column and latest date SQL Select Distinct column and latest date sql-server sql-server

SQL Select Distinct column and latest date


This is actually pretty easy to do using simple aggregation, like so:

select URL, max(DateVisited)from <table>group by URL


This is usually done using row_number():

select t.*from (select t.*,             row_number() over (partition by url order by datevisited desc) as seqnum      from t     ) twhere seqnum = 1;

This allows you to get all the columns associated with the latest record.