Calculate multiple values same field

foshizzle

Registered User.
Local time
Today, 12:58
Joined
Nov 27, 2013
Messages
277
I have a table where there are multiple vehicles, each identified by their vehiclenumber. Each record holds the vehiclenumber, date and odometer reading. I need to figure out how to calculate records in this table per each vehiclenumber.

Below is a code that works, but only when i have each vehicle with the same vehiclenumber.

Code:
SELECT tblOdometer.VehicleNum, tblOdometer.ODate, tblOdometer.Odometer, tblOdometer.Odometer AS OdomAlias, Nz(DLast("Odometer","tblOdometer","[Odometer] < " & [OdomAlias]),0) AS Previous, [Odometer]-[Previous] AS Difference
FROM tblOdometer;
 
Well, that looks almost exactly like what i need. but when I edit the sample to match my table and fields, im pulling nad data adter so many records for each vehicle. see the text doc attached.

Code:
SELECT tblOdometer.ID, tblOdometer.ODate, tblOdometer.Odometer, (SELECT TOP 1 Dupe.Odometer                 
   FROM tblOdometer AS Dupe                     
   WHERE Dupe.VehicleNum = tblOdometer.VehicleNum 
     AND Dupe.ODate < tblOdometer.ODate   
   ORDER BY Dupe.ODate DESC, Dupe.ID) AS PriorValue
FROM tblOdometer;
 

Attachments

I think you need another step before creating the subquery. If you do the following query it will give you the keys to pull only the latest date for each vehicle which you can then re-join with you base table to get the latest reading. Use this with your current solution.

Code:
SELECT tblOdometer.VehicleNum, Max(tblOdometer.ODate) AS LatestDate
FROM tblOdometer
GROUP BY tblOdometer.VehicleNum;

I attach the solution also.

hth
Chris
 

Attachments

Thanks. After after looking at it, Instead of just top 1, I am going to need the running difference. So i tried removing the Top 1 statement and just a select but its telling me "At most one record can be returned by this subquery"
 

Users who are viewing this thread

Back
Top Bottom