Query for getting value from another record in same table and filter by difference greater than a gap threshold

Will offer one more contribution – option with VBA code to get the Current/Previous pairs. This does require saving records to table. Tested and runs in a snap.

Sub GetGap()
Dim intTH As Integer, x As Integer, strGID As String
Dim rsT1 As DAO.Recordset, rsT2 As DAO.Recordset
CurrentDb.Execute "DELETE FROM Temp"
Set rsT1 = CurrentDb.OpenRecordset("SELECT * FROM Temporary ORDER BY GlobalID, ItemID DESC;")
Set rsT2 = CurrentDb.OpenRecordset("SELECT * FROM Temp;")
strGID = rsT1!GlobalID
x = 1
While Not rsT1.EOF
    If strGID = rsT1!GlobalID Then
        If x = 1 Then
            rsT2.AddNew
            rsT2!GlobalID = strGID
            rsT2!CurItemID = rsT1!ItemID
            rsT2!CurDate = rsT1![Version Date]
            x = 2
        ElseIf x = 2 Then
            rsT2!GlobalID = strGID
            rsT2!PreItemID = rsT1!ItemID
            rsT2!PreDate = rsT1![Version Date]
            x = 3
        End If
        If Not rsT1.EOF Then rsT1.MoveNext
    Else
        If x = 3 Then rsT2.Update
        strGID = rsT1!GlobalID
        x = 1
    End If
    If rsT1.EOF Then rsT2.Update
Wend
End Sub

Then a query can easily calculate the Gap and filter records.

SELECT Temp.GlobalID, Temp.CurItemID, Temp.CurDate, Temp.PreDate, Temp.PreItemID, [CurDate]-[PreDate] AS Gap
FROM Temp
WHERE ((([CurDate]-[PreDate])>Int([Enter Threshold])));

Or the code can be expanded to also calc the Gap and save only records that meet the threshold requirement, just a bit more complicated.

Leave a Comment