Need help on query - average of most recent 3 results

P

Philip Lo

Hi,

I have a table with 3 columns, col 1 is date time, col 2 is text, and col 3
is number. Is it possible to have one single query that calculates the
average of 3 for col 3 (selection of 3 rows is based on those with most
recent time stamp in col 1) group by col 2 ?

Example:
------------------
col 1, col 2, col 3
------------------
1 Oct 2005, A01, 20;
2 Oct 2005, A01, 25;
3 Oct 2005, A01, 30;
4 Oct 2005, A01, 35;
5 Oct 2005, A02, 40;
6 Oct 2005, A02, 45;
7 Oct 2005, A02, 50;
8 Oct 2005, A02, 55;

After query:
-------------------------------------------
Average of most recent 3 results, col 2
-------------------------------------------
(25+30+35)/3=30, A01;
(45+50+55)/3=50, A02;

Thanks....

regards,
Philip
 
M

Michel Walsh

Hi,


A first query can rank the records:


SELECT a.col1, a.col2, a.col3, COUNT(*) As Rank
FROM myTable As a INNER JOIN myTable As b
ON a.col2=b.col2 AND a.col1 <= b.col1
GROUP BY a.col1, a.col2, a.col3
HAVING COUNT(*) <= 3



A second query make a total query on the previous one:


SELECT a.col2, AVG(a.col3)
FROM previousQuery
GROUP BY a.col1



Hoping it may help,
Vanderghast, Access MVP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top