Hi Jeff
If you just want the maximum (i.e. latest) date and time, for each
patient, then (assuming acct# corresponds to patient) this will do it:
SELECT acct#,Max(datetimeoftest) AS LatestTestData FROM....[table(s)]
GROUP BY acct#
If you want the results of the latest test as well, it gets more
complicated - as you said, you need to use subqueries. I've come
across this one often, and wished there was a "select these columns
from the row where this other column is the MAX" functionality in SQL.
Now I put it that way I've just realised why there isn't: because more
than one row could (theoretically) be identified as the "max" row - if
a patient had two tests at exactly the same time. Not a problem in
this case, I guess.
To get the latest result, try this:
SELECT tests.* FROM
(SELECT acct#,Max(dateandtimeoftest) AS LatestTestDate FROM [test
table(s)]
GROUP BY acct#) latest
INNER JOIN
[test table] tests
ON
latest.acct#=test.acct# AND
latest.LatestTestDate=test.dateandtimeoftest
This should only give multiple results if a patient has had two tests
at exactly the same time, and these two are the latest tests.
Another way of doing it is to join the table to itself, finding all
test dates which have no later test date for the same patient:
SELECT earlier.* FROM
[test table] earlier
LEFT JOIN
[test table] later
ON
earlier.acct#=later.acct# AND
earlier.dateandtime<later.dateandtime
WHERE later.[A non-nullable column] IS NULL
let me know if this helps!
cheers
Seb