Select the product you need help with
ACC2000: How to Create a "Top N Values Per Group" QueryArticle ID: 210039 - View products that this article applies to. This article was previously published under Q210039 Moderate: Requires basic macro, coding, and interoperability skills.
This article applies only to a Microsoft Access database (.mdb). On This PageSUMMARY
This article shows you two methods that you can use to create queries that
list only the top n items per group. By using either one of these methods, you can create a query that displays only the top five salespeople for each region.
MORE INFORMATION
To list only the top n items within a group in a query, you must specify a criteria that dynamically reads the grouping column in the query and limits the item column to the top n values within each group. Method 1 uses a SQL subquery to dynamically generate a list of the top n items for each group, and then uses this list as the criteria for the item column by using the In operator. Method 2 uses a user-defined function to return the nth item within a specific group, which is then used with the >= operator to return the nth-and-greater items. Method 1Follow these steps to create a query in the Northwind sample database that displays the top three UnitsInStock per CategoryID. The query uses a SQL subquery, which returns the top three UnitsInStock, given a specific CategoryID, and then uses the In operator to limit the records in the main query.NOTE: In the criteria example in step 5, an underscore (_) at the end of a line is used as a line-continuation character. Remove the underscore from the end of the line when re-creating the criteria. CAUTION: If you follow the steps in this example, you modify the sample database Northwind.mdb. You may want to back up the Northwind.mdb file and follow these steps on a copy of the database.
Method 2Follow these steps to create a query in the Northwind sample database that displays the last five orders placed per customer. The query uses a criteria function called NthInGroup() that returns the fifth most recent OrderDate, given a specific CustomerID. If you use the >= operator along with this function, all orders that were placed on or after the fifth most recent OrderDate for each customer will be returned.CAUTION: If you follow the steps in this example, you modify the sample database Northwind.mdb. You may want to back up the Northwind.mdb file and follow these steps on a copy of the database.
REFERENCESFor more information about subqueries, click Microsoft Access Help on the Help menu, type sql subqueries in the Office Assistant or the Answer Wizard, and then click Search to view the topic. PropertiesArticle ID: 210039 - Last Review: June 29, 2004 - Revision: 2.0
| Article Translations
|


Back to the top








