Create a query that finds the most recent color for every ID. Let's call that query LatestChanges. It will have two columns, let's call them ID and last_changed. Join this query with the table of changing colors, let's call that table ColorChanges; it already has a name but you didn't mention it.
I will assume that the date and time of the change are stored in one column named date_changed.
The SQL defining LatestChanges is:
Code:
SELECT ID,
MAX(date_changed) AS "last_changed"
FROM ColorChanges
GROUP BY ID
The SQL joining the new query and the existing table is:
Code:
SELECT ID,
color
FROM ColorChanges
JOIN LatestChanges ON ColorChanges.ID = LatestChanges.ID
AND ColorChanges.date_changed = LatestChanges.last_changed
This is a technique that you can apply in any situation where you need to show both an aggregate result and many of the descriptive attributes of an entity. Create a view to obtain the aggregate for all of the entities, summarize by the ID values; then join that view to a table with all of the interesting details about each entity.
The particular example here is a variation in that we do not have a table of the entities referred to by the ID. If we did then the join condition would be a little different. Suppose these IDs are referring to Chameleons and we have a table of information about the Chameleons in our garden, ID, name, date_of_hatch, tail_missing, that kind of thing.
We could use the aggregate query defined above to report on the current color of each Chameleon. In fact let's keep track of where the fellas were sitting when the color changed in the table of ColorChanges in a columnn named sitting_on.
Code:
SELECT Chameleons.name,
ColorChanges.color,
ColorChanges.sitting_on,
LatestChanges.last_changed
FROM Chameleons
JOIN ColorChanges ON Chameleons.ID = ColorChanges.ID
JOIN LatestChanges ON Chameleons.ID = LatestChanges.ID
AND ColorChanges.date_changed =
LatestChanges.last_changed
Well, time to go back to work.