richardp

MS Access Top N Query with Grouping

Apr 23rd, 2014
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. A Useful Guide I Found for Creating TOP N Queries on MS Access
  2. With Grouping
  3.  
  4. 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.
  5.  
  6. Method 1
  7.  
  8. 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.
  9.  
  10. 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.
  11.  
  12. Open the sample database Northwind.mdb.
  13. Click the Queries tab, and then click New.
  14. Click Design View, and then click OK.
  15. In the Show Table dialog box, add the Categories and the Products tables, and then click Close.
  16. Add the following fields to the query grid:
  17. Field: CategoryName
  18. Sort: Ascending
  19.  
  20. Field: ProductName
  21.  
  22. Field: UnitsInStock
  23. Sort: Descending
  24. Criteria: In (Select Top 3 [UnitsInStock] From Products Where _
  25. [CategoryID]=[Categories].[CategoryID] Order By [UnitsInStock] Desc)
  26. Run the query. Note that the query returns the top three UnitsInStock for each category.
  27.  
  28.  
  29. From: http://support.microsoft.com/kb/153747
Advertisement
Add Comment
Please, Sign In to add comment