Skip to content
Advertisement

Access SQL Query to display the most recent date only for duplicate records

Below is my current MS Access SQL that displays all records. However, If there is a duplicate account record, it should only display the record with the latest date ComputationPeriodStartingDate

Dataset example. All non duplicates should be returned, Account 1005 is the only duplicate of which only the one dated 12/1/2021 should be included in return

Account ComputationPeriodStartingDate LastName Categories
10001 12/1/2021 Kent Active
10005 12/1/2021 Nashton Active
10005 6/1/2021 Nashton Active
10011 1/1/2022 Steele Active
10015 12/1/2021 Rich Active

I dont know how to get my current SQL to filter properly.

SELECT [TDS LOANS].Account, [TDS Escrow Projections].ComputationPeriodStartingDate, [TDS LOANS].LastName, [TDS LOANS].Categories
FROM [TDS Escrow Projections] INNER JOIN [TDS LOANS] ON [TDS Escrow Projections].LoanRecID = [TDS LOANS].RecID
WHERE ((([TDS LOANS].PrinBal)<>0))
ORDER BY [TDS LOANS].Account, [TDS Escrow Projections].ComputationPeriodStartingDate DESC;

Expected Result

Account ComputationPeriodStartingDate LastName Categories
10001 12/1/2021 Kent Active
10005 12/1/2021 Nashton Active
10011 1/1/2022 Steele Active
10015 12/1/2021 Rich Active

Advertisement

Answer

Try using sub-query:

SELECT a.Account, a.ComputationPeriodStartingDate, a.LastName, a.Categories
    FROM
      (
SELECT [TDS LOANS].Account, [TDS Escrow Projections].ComputationPeriodStartingDate, [TDS LOANS].LastName, [TDS LOANS].Categories
    FROM [TDS Escrow Projections] INNER JOIN [TDS LOANS] ON [TDS Escrow Projections].LoanRecID = [TDS LOANS].RecID
    WHERE ((([TDS LOANS].PrinBal)<>0))
    ORDER BY [TDS LOANS].Account, [TDS Escrow Projections].ComputationPeriodStartingDate DESC
) 
    as a
        INNER JOIN
        (
SELECT Account, MAX(ComputationPeriodStartingDate) as max_date
        FROM
    (SELECT [TDS LOANS].Account, [TDS Escrow Projections].ComputationPeriodStartingDate, [TDS LOANS].LastName, [TDS LOANS].Categories
    FROM [TDS Escrow Projections] INNER JOIN [TDS LOANS] ON [TDS Escrow Projections].LoanRecID = [TDS LOANS].RecID
    WHERE ((([TDS LOANS].PrinBal)<>0))
    ORDER BY [TDS LOANS].Account, [TDS Escrow Projections].ComputationPeriodStartingDate DESC
)
        GROUP BY Account) as b
        ON a.Account=b.Account AND a.ComputationPeriodStartingDate = b.max_date

The sub-query will return max of ComputationPeriodStartingDate for each Account. Then we join it with the table on Account and max_date.

Note: Table name was not mentioned by you. Hence update the table name accordingly.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement