So I'm trying to create a query that will produce an average (totals) column based on the TOP 3 records associated with two other key field values. Basically an average of the three most recent events. I can easily create the query to do the OVERALL averages, but whenever I try to use the built-in TOP N tool it only returns the top 3 accounts or locations, not an average of the TOP 3 results for each account and location.
Here's the code I've got:
The bold statement in the code is what I'm trying to only pull the 3 most recent matching records to produce the average for, this has been driving me nuts for a few days trying to solve it, and it seems like it should be simple.
There's a date field in dbo_CompletedAccountDrives and I can even limit it to only results from "X" time period, but that doesn't help because my end users want last 3, regardless of time elapsed.
Any help is greatly appreciated.
Here's the code I've got:
Code:
SELECT dbo_CompletedAccountDrives.accountid, dbo_rpt_DriveMaster.LocationID, [B]Round(Avg([dbo_DriveProjectionAndCollectedTotals]![ProductsCollected]),0) AS Products[/B]
FROM (dbo_rpt_DriveMaster INNER JOIN dbo_DriveProjectionAndCollectedTotals ON dbo_rpt_DriveMaster.DriveID = dbo_DriveProjectionAndCollectedTotals.DriveID) INNER JOIN dbo_CompletedAccountDrives ON dbo_rpt_DriveMaster.AccountID = dbo_CompletedAccountDrives.accountid
GROUP BY dbo_CompletedAccountDrives.accountid, dbo_rpt_DriveMaster.LocationID
ORDER BY dbo_CompletedAccountDrives.accountid, dbo_rpt_DriveMaster.LocationID;
The bold statement in the code is what I'm trying to only pull the 3 most recent matching records to produce the average for, this has been driving me nuts for a few days trying to solve it, and it seems like it should be simple.
There's a date field in dbo_CompletedAccountDrives and I can even limit it to only results from "X" time period, but that doesn't help because my end users want last 3, regardless of time elapsed.
Any help is greatly appreciated.