select state_name, county_name, population
from (
select
s.name state_name,
c.name county_name,
c.population,
row_number() over(partition by s.state_code order by population desc) rn
from
states s
inner join
counties c on s.state_code = c.state_code
) s
where rn <= 5
order by state_name, population desc