lundi 22 décembre 2014

Retrieving n rows per group


I often need to select a number of rows from each group in a result set.


For example, I might want to list the 'n' highest or lowest recent order values per customer.


In more complex cases, the number of rows to list might vary per group (defined by an attribute of the grouping/parent record). This part is definitely optional/for extra credit and not intended to dissuade people from answering.


What are the main options for solving these types of problems in SQL Server 2005 and later? What are the main advantages and disadvantages of each method?


AdventureWorks examples (for clarity, optional)



  1. List the five most recent recent transaction dates and IDs from the TransactionHistory table, for each product that starts with a letter from M to R inclusive.

  2. Same again, but with n history lines per product, where n is five times the DaysToManufacture Product attribute.

  3. Same, for the special case where exactly one history line per product is required (the single most recent entry by TransactionDate, tie-break on TransactionID.





Aucun commentaire:

Enregistrer un commentaire