You have added the table twice in the from clause with NO join. It should NOT
be in the FROM clause twice
SELECT [Monthly Miles from Master FD 03].EquipmentID
, [Monthly Miles from Master FD 03].YearMonth
, [Monthly Miles from Master FD 03].Mileage
, (SELECT TOP 1 [Dupe].Mileage
FROM [Monthly Miles from Master FD 03] AS [Dupe]
WHERE [Dupe].EquipmentID = [Monthly Miles from Master FD 03].EquipmentID
AND [Dupe].YearMonth < [Monthly Miles from Master FD 03].YearMonth
ORDER BY [Dupe].[YearMonth] DESC) AS PreviousMileage
FROM [Monthly Miles from Master FD 03]
WHERE (([Monthly Miles from Master FD 03].EquipmentID)="UD793");
When you had the table in the FROM clause twice with no join it created a row
for every combination of the records. So if you had 26 UD793 records and 1000
records total, you were going to process 26,000 rows that had UD793.
As I said I would use something like the following instead of the above. Note
that I have assigned an "alias" to [Monthly Miles from Master FD 03] in the
main query. It shortens typing and it makes things clearer (for me) when I am
constructing queries. If it bothers you, then remove the M03 and replace it
with [Monthly Miles from Master FD 03] - except of course in the from clause
where you should just remove "as M03".
SELECT M03.EquipmentID
, M03.YearMonth
, M03.Mileage
, (SELECT Max([Dupe].Mileage)
FROM [Monthly Miles from Master FD 03] AS [Dupe]
WHERE [Dupe].[EquipmentID] = M03.[EquipmentID]
AND Dupe.Mileage < M03.[Mileage]
AND Dupe.YearMonth < M03) AS PreviousMileage
FROM [Monthly Miles from Master FD 03] as M03
John Spencer
Access MVP 2002-2005, 2007-2010
The Hilltop Institute
University of Maryland Baltimore County
John,
I got the query to run. However the query appears to be stuck in a loop. I
limited the selection to UD793, there should have been 26 records. There were
many interations of 26 records, I suspect there would have been at least 650
records. How do I code the query so it only runs once and does not keep
accessing the same records? Here is code that I used to get the query to run:
(I had to add the table and alias in the properties window)
SELECT [Monthly Miles from Master FD 03].EquipmentID, [Monthly Miles from
Master FD 03].YearMonth, [Monthly Miles from Master FD 03].Mileage, (SELECT
TOP 1 [Dupe].Mileage FROM [Monthly Miles from Master FD 03] AS [Dupe] WHERE
[Dupe].EquipmentID = [Monthly Miles from Master FD 03].EquipmentID AND
[Dupe].YearMonth < [Monthly Miles from Master FD 03].YearMonth ORDER BY
[Dupe].[YearMonth] DESC) AS PreviousMileage
FROM [Monthly Miles from Master FD 03], [Monthly Miles from Master FD 03] AS
Dupe
WHERE (([Monthly Miles from Master FD 03].EquipmentID)="UD793");
.