Это ваш запрос:
select countryName, balance
from main.country c join
main.person p
on c.countryId = p.countryId
where balance = (select MAX(balance)
from main.person p2 join
main.country c2
on c2.countryId = p2.countryId
where c.countryId = c2.countryId and p.countryId = p2.countryId
)
order by countryName;
Из того, что я могу сказать, вы хотите получить максимальный баланс в каждой стране, а также дубликаты, если таковые имеются.Вы можете получить их, используя:
select top (1) with ties c.countryName, p.balance
from main.country c join
main.person p
on c.countryId = p.countryId
order by rank() over (partition by c.countryId order by p.balance desc);
Чтобы получить их в порядке по названию страны, вам нужен подзапрос:
select cp.*
from (select top (1) with ties c.countryName, p.balance
from main.country c join
main.person p
on c.countryId = p.countryId
order by rank() over (partition by c.countryId order by p.balance desc)
) cp
order by countryName;