You only want years where there were customers. So WHERE customers_nb > 0
.
You want one record per company. So GROUP BY company_id
.
You want the most recent year. So MAX(year)
.
Only problem: You want the number of customers in the found year. To retrieve that, we will have to find the year first and then join the table again to get the additional data.
select mytable.*
from mytable
inner join
(
select company_id, max(year) as year
from mytable
where customers_nb > 0
group by company_id
) theyear on theyear.company_id = mytable.company_id and theyear.year = mytable.year;
EDIT (after acceptence of above answer):
Here is another way of writing the query: Give me all records where no later record exists.
select mytable.*
from mytable
where customers_nb > 0
and not exists
(
select *
from mytable later
where later.customers_nb > 0
and later.company_id = mytable.company_id and later.year > mytable.year
);
And here is the same with an outer join. The trick is to outer join later entries and then remove records where later entries could be found. This looks slow, because it can be assumed to create a big intermediate result (all later entries joined with each record in the table) that are not actually needed. However, MySQL is known for preferring joins over other operations. And with many comapnies and few years the intermediate result wouldn't be that big.
select mytable.*
from mytable
left join mytable later on later.company_id = mytable.company_id and later.year > mytable.year and later.customers_nb > 0
where mytable.customers_nb > 0
and later.company_id is null;