select * from stops a inner join (select max(table_period_id) as max_table_period_id, stop_id from stops group by stop_id) b on a.stop_id = b.stop_id and a.table_period_id = b.max_table_period_id
