I have a table which I want to get the latest entry for each group. Here\'s the table:
DocumentStatusLogs
Table
|ID| DocumentID | Status
SELECT * FROM
DocumentStatusLogs JOIN (
SELECT DocumentID, MAX(DateCreated) DateCreated
FROM DocumentStatusLogs
GROUP BY DocumentID
) max_date USING (DocumentID, DateCreated)
What database server? This code doesn't work on all of them.
Regarding the second half of your question, it seems reasonable to me to include the status as a column. You can leave DocumentStatusLogs
as a log, but still store the latest info in the main table.
BTW, if you already have the DateCreated
column in the Documents table you can just join DocumentStatusLogs
using that (as long as DateCreated
is unique in DocumentStatusLogs
).
Edit: MsSQL does not support USING, so change it to:
ON DocumentStatusLogs.DocumentID = max_date.DocumentID AND DocumentStatusLogs.DateCreated = max_date.DateCreated