Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- A Useful Guide I Found for Creating TOP N Queries on MS Access
- With Grouping
- In order 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 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 1
- The following example shows you how 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.
- Open the sample database Northwind.mdb.
- Click the Queries tab, and then click New.
- Click Design View, and then click OK.
- In the Show Table dialog box, add the Categories and the Products tables, and then click Close.
- Add the following fields to the query grid:
- Field: CategoryName
- Sort: Ascending
- Field: ProductName
- Field: UnitsInStock
- Sort: Descending
- Criteria: In (Select Top 3 [UnitsInStock] From Products Where _
- [CategoryID]=[Categories].[CategoryID] Order By [UnitsInStock] Desc)
- Run the query. Note that the query returns the top three UnitsInStock for each category.
- From: http://support.microsoft.com/kb/153747
Advertisement
Add Comment
Please, Sign In to add comment