Finding Only the Most Current Row

Finding Only the Most Current Row

The Situation: I need to define some queries to extract data from an existing database (I am using MS Access 2.0). It consists of only two tables, from which the relevant columns are:

    Headers:  id, unitno, date, time    Measurements:  id, measno, measresult
The table called Headers holds data for a test (electronics production).Every time a test is performed, a unique ID is given to this test. If a Unit is tested more than one time, the same UnitNo will be present with different IDs and Times (and perhaps Dates). In the Measurements table,the results from the test are stored. Each test consists of severalmeasurements (several MeasNo’s), and the ID refers to the Headers table. If a test consists of say 50 measurements, this table will hold 50 times the records in Headers (50 for each ID). By looking up a UnitNo in the Headers table, the corresponding MeasNo’s and MeasResults can beretrieved.

The Problem: In some situations, only the latest test of a specific Unit is to be analyzed. I need to lookup the Headers table for a UnitNo, and return the ID for the latest test of that UnitNo. I tried to ORDER BY UnitNo, Date DESC, Time DESC in the Headers table. Then I just need to pick the ID of the first entry of each UnitNo. How do I do that? I tried to use GROUP BY UnitNo, but then I can’t get the ID. If I also GROUP BY ID (to get it), all entries of UnitNo are returned. I also tried to use SELECT TOP 1, but can’t get it to SELECT for each UnitNo. I tried to make different nested SELECTs, but can’t seem to get it right.How can I get the desired result?

I’d recommend:

SELECT id, unitno, date, time FROM Headers    WHERE date+time IN        (SELECT MAX(date+time) FROM Headers        GROUP BY unitno);
Thanks to Carl Federl for pointing out that the above solutionsometimes reports duplicate rows. A correlated subquery can beused as a better solution:
    SELECT A.unitno,, A.datetime FROM Headers AS A    WHERE A.datetime IN         (SELECT MAX(datetime) FROM Headers AS B WHERE B.unit = A.unit);


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist