Given a very simplified table with the columns
Name, Action, Status, Timepoint
1 "A" "Open" "OK" "2012-09-04 10:10:00"
2 "A" "Close" "OK" "2012-09-04 10:05:00"
3 "A" "Close" "ERROR" "2012-09-04 10:02:00"
4 "B" "Look" "NICE" "2012-09-04 10:05:00"
5 "B" "Blow" "COLD" "2012-09-04 10:00:00"
6 "C" "Laugh" "OK" "2012-09-04 10:02:00"
7 "C" "Laugh" "MUTE" "2012-09-04 10:00:00"
How do I most efficiently select each row for a combination of Name and Action but only of the Action of the newest Timepoint?
In the above example it would return rows
1, 2, 4, 5, 6
The working implementation fetches the rows and uses a sub query to only return if there are 0 rows with the same Name, Action combination of a newer Timepoint. But that seems very inefficient when the data set becomes large. It’s something like this
SELECT Name, Action, Status, Timepoint
FROM foobar
WHERE Name IN (... Names of interest ...) AND
Status IN (... statuses of interest ...) AND
(SELECT COUNT(*) FROM foobar AS t2 WHERE t2.Name = Name AND t2.Status = Status AND t2.Timepoint > Timepoint) = 0
order by Name, Timepoint
1 Answer