Select top n records from each category within same table
问题 I've a purchase detail table that has item id , purchase date , and item unit cost . I want to get an avg of an item purchase cost by selecting latest top 2 records from each item id. Item id, purchase date, unitprice 1 3/1/2012 10 1 3/11/2012 8 2 3/1/2012 10 2 3/11/2012 10 1 2/1/2012 9 3 3/1/2012 10 3 3/11/2012 1 3 3/12/2012 13 I'm using sql server 2008 r2 回答1: Try this: ;WITH CTE AS ( SELECT [Item id], [purchase date], unitprice, ROW_NUMBER() OVER(PARTITION BY [Item id] ORDER BY [purchase