MySQL Select Latest Date - Single Table -


i have table looks , want ids (insp_id) of newest insp_date 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 "in" strategy select latest record in table (datetime field) , others gives me double since 1 loc_id's latest date may non-latest another:

select insp_id, loc_id, insp_active, insp_date insp  insp_active = 1  , insp_date in(select max(insp_date) insp insp_active = 1 group loc_id) order loc_id asc, insp_date desc; 

i setup sql fiddle adding various group , max not seem it. feel need join on sub-query or similar not sure @ point.

http://sqlfiddle.com/#!2/f95e0/1

thanks, andrew

you need retrieve max date each location, , then, max insp_id date

query 1:

select insp.loc_id, max(insp.insp_id) insp inner join     (select loc_id, max(insp_date) insp_date      insp       insp_active = 1       group loc_id) mdate on mdate.loc_id = insp.loc_id ,                                    mdate.insp_date = insp.insp_date insp_active = 1  group insp.loc_id 

results:

| loc_id | max(insp.insp_id) | |--------|-------------------| |      1 |                 1 | |      2 |                40 | |      3 |                48 | |      4 |                37 | |      5 |                49 | |      6 |                39 | |      7 |                50 | |      8 |                46 | 

update :

if there 1 active inspection specific date, , newest active, can :

select insp.loc_id, insp.insp_id insp inner join     (select loc_id, max(insp_date) insp_date      insp       insp_active = 1       group loc_id) mdate on mdate.loc_id = insp.loc_id ,                                    mdate.insp_date = insp.insp_date insp_active = 1  

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -