Сначала создайте CTE
, который возвращает все округа, содержащие все фамилии, которые вы ищете, а затем используйте RANK()
оконную функцию:
with cte as (
select county,
sum(surname = 'Griffin') counter1,
sum(surname = 'Griffy') counter2,
sum(surname = 'Griffey') counter3
from census_data
where surname in ('Griffin', 'Griffy', 'Griffey')
group by county
having counter1 * counter2 * counter3 > 0
)
select county, min(counter1, counter2, counter3) least_common_name_counter
from (
select *, rank() over (order by min(counter1, counter2, counter3)) rank
from cte
)
where rank = 1
или если вы хотите получить результаты для всех округов:
with cte as (
select county,
sum(surname = 'Griffin') counter1,
sum(surname = 'Griffy') counter2,
sum(surname = 'Griffey') counter3
from census_data
where surname in ('Griffin', 'Griffy', 'Griffey')
group by county
having counter1 * counter2 * counter3 > 0
)
select county, min(counter1, counter2, counter3) least_common_name_counter
from cte