Get top 'n' records by report_id
        Posted  
        
            by Skudd
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Skudd
        
        
        
        Published on 2010-05-31T22:03:21Z
        Indexed on 
            2010/05/31
            22:13 UTC
        
        
        Read the original article
        Hit count: 213
        
I have a simple view in my MSSQL database. It consists of the following fields:
report_id INT
ym VARCHAR -- YYYY-MM
keyword VARCHAR(MAX)
visits INT
I can easily get the top 10 keyword hits with the following query:
SELECT TOP 10 *
FROM top_keywords
WHERE ym BETWEEN '2010-05' AND '2010-05'
ORDER BY visits DESC
Now where it gets tricky is where I have to get the top 10 records for each report_id in the given date range (ym BETWEEN @start_date AND @end_date). 
How would I go about getting the top 10 for each report_id? I've stumbled across suggestions involving the use of ROW_NUMBER() and RANK(), but have been vastly unsuccessful in their implementation.
© Stack Overflow or respective owner