View Single Post
  #1  
Old May 29th, 2010, 11:24 AM posted to microsoft.public.access.queries
Mike P
external usenet poster
 
Posts: 23
Default Select Top with aggregate function

I have a SQL statement that returns an count and average amount paid for a
customer in a table. I wish to alter the SQL so I only get the first X rows
returned. The SQL below is working to return all records.
SELECT Count(*) AS Expr1, Avg(tblPayment.amountPaid) AS Expr2
FROM tblPayment
WHERE (((tblPayment.Customer)="Doe") AND ((tblPayment.amountPaid) Is Not
Null));

I am currently getting 8 records returned for this query since that is how
many are in the data base. When I add TOP 5 to the query, I still get a
count() of 8 returned. Any ideas how to fix this?

SELECT TOP 5 Count(*) AS Expr1, Avg(tblPayment.amountPaid) AS Expr2
FROM tblPayment
WHERE (((tblPayment.Customer)="Doe") AND ((tblPayment.amountPaid) Is Not
Null));

I tried adding a GROUP BY and that returned the 5 records, but it no longer
returned an AVG or a COUNT. It actually returned 5 records. I want the
count() and avg() of the top 5 records. Not the top 5 records.

Any ideas?