In this example, we get the latest comment for multiple contacts:
;with cte as (
select ROW_NUMBER() OVER(PARTITION BY contactid
ORDER BY datecreated desc) AS rownum,content from comments where contactid in (
345823,175779,332941,315655,341843)
) select * from cte where rownum = 1
;with cte as (...)
Defines a CTE named cte to organize the logic before the final SELECT.select ROW_NUMBER() OVER(PARTITION BY contactid ORDER BY datecreated desc) AS rownum, content
Uses theROW_NUMBER()window function to assign a unique row number to each comment percontactid, ordered bydatecreateddescending.This means the most recent comment for each
contactidwill getrownum = 1.from comments where contactid in (...)
Filters the comments table to only include rows where contactid is one of the specified values:select * from cte where rownum = 1
Selects only the rows from the CTE where rownum = 1, i.e., the most recent comment for eachcontactid.