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)
- List the five most recent recent transaction dates and IDs from the
TransactionHistorytable, for each product that starts with a letter from M to R inclusive.
- Same again, but with
nhistory lines per product, where
nis five times the
- Same, for the special case where exactly one history line per product is required (the single most recent entry by
TransactionDate, tie-break on