Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: SQL Server
Expertise: Beginner
Mar 24, 1997

Finding Only the Most Current Row

Question:
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 several measurements (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 be retrieved.

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?

Answer:
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 solution sometimes reports duplicate rows. A correlated subquery can be used as a better solution:
    SELECT A.unitno, A.id, A.datetime FROM Headers AS A
    WHERE A.datetime IN 
        (SELECT MAX(datetime) FROM Headers AS B WHERE B.unit = A.unit);
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date