I have a table that looks like this and I want to get the IDs (insp_id) of the newest insp_date for each loc_id.
create table insp (
insp_id int (10),
loc_id int (11),
insp_type varchar (150),
insp_date date ,
insp_active tinyint (2),
insp_created timestamp ,
insp_modified timestamp
);
I tried the "IN" strategy from Select latest record in table (datetime field) and others but that gives me double since one loc_id's latest date may be the non-latest for another:
SELECT insp_id, loc_id, insp_active, insp_date
FROM insp
WHERE insp_active = 1
AND insp_date IN(SELECT MAX(insp_date) FROM insp WHERE insp_active = 1 GROUP BY loc_id)
ORDER BY loc_id ASC, insp_date DESC;
I setup a SQL Fiddle but adding various GROUP BY and MAX does not seem to get it. I feel like I need to join on a sub-query or something similar but am not sure at this point.
http://sqlfiddle.com/#!2/f95e0/1
Thanks, Andrew