开发者

MS Access get Average only if one record meets criteria

开发者 https://www.devze.com 2023-03-11 10:35 出处:网络
In MS Access I am trying to get an average of data but only when the last record of each set is larger than a value. almost have it but cant get the last part. So my data looks like so:

In MS Access I am trying to get an average of data but only when the last record of each set is larger than a value. almost have it but cant get the last part. So my data looks like so:

 CarID  WeekOf          NumDataPoints   Fuel
 3AA    May-14-2011     4               300
 7BB    May-14-2011     9               250

 3AA    May-21-2011     35              310
 7BB    May-21-2011     7               275

 3AA    May-28-2011     24              355    
 7BB   开发者_Python百科 May-28-2011     4               280

My recordset should include the average of the fuel only for those cars that have a current point count >= 5. So the current week is May-28-2011 and the only car with a point count >= 5 is car 3AA. Doesn't matter what the point count is in other weeks. i tried

 SELECT CarId, Avg(Fuel) AS AvgF
 FROM tblCars
 WHERE WeekOf>=#5/14/2011# And WeekOf<=#5/28/2011# AND
       CarId = (SELECT CarId FROM tblCars 
                WHERE WeekOf=#5/28/2011# AND NumDataPoints>=5)
 GROUP BY CarId;

I should get back

 CarID AvgF 
 3AA   321.6666

How would I put a criteria only on the current week but get back three weeks when it does pass the criteria?


You can use this query to show which cars have 5 or more NumDataPoints.

SELECT CarID FROM tblCars
WHERE
    (((WeekOf)=#2011-05-28#)
    AND ((NumDataPoints)>=5));

And this to average the Fuel values for each car over the 3 week range.

SELECT CarID, Avg(Fuel) AS AvgF
FROM tblCars
WHERE
    (((WeekOf)>=#2011-05-14#
    And (WeekOf)<=#2011-05-28#))
GROUP BY CarID;

INNER JOIN them on CarID so the first query selects a subset of the cars from the second query.

SELECT whichcars.CarID, fuel_averages.AvgF
FROM
    [SELECT CarID FROM tblCars
     WHERE
        (((WeekOf)=#2011-05-28#)
        AND ((NumDataPoints)>=5))
    ]. AS whichcars
    INNER JOIN [SELECT CarID, Avg(Fuel) AS AvgF
                FROM tblCars
                WHERE
                    (((WeekOf)>=#2011-05-14#
                    And (WeekOf)<=#2011-05-28#))
                GROUP BY CarID
                ]. AS fuel_averages
    ON whichcars.CarID = fuel_averages.CarID;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号