如何从 ERD 图表中加入最大数量的政策和没有政策的客户?

How do I JOIN customers with maximum number of policies and no policies from an ERD diagram?

我想编写一个查询来显示已购买最多保单的客户的姓名,然后显示未购买保单的客户的姓名。

select customer.first_name
from customer
join customer_policy on customer.id = customer_policy.customer_id
having count(customer_policy.policy_id) = select max(count(policy_id)) from customer_policy

union all

select customer.first_name
from customer
full outer join customer_policy on customer.id = customer_policy.customer_id
where count(customer_policy.policy_id) = 0

我正在使用 UNION ALL 合并两个查询,但无论我尝试以何种方式执行此操作,我最终都会收到聚合错误或错误答案。

我做错了什么?

我正在使用的 ERD:

https://i.stack.imgur.com/67BA6.png

使用 cte 聚合和returns每个客户的保单数量和最大保单数量。
最后 select 来自 cte 的只有拥有最大保单数量或 0 的客户行:

WITH cte AS (
  SELECT c.first_name, 
         COUNT(p.policy_id) number_of_policies,
         MAX(COUNT(p.policy_id)) OVER () max_policies
  FROM customer c LEFT JOIN customer_policy p
  ON p.customer_id = c.id
  GROUP BY c.id, c.first_name
)
SELECT first_name, number_of_policies
FROM cte
WHERE number_of_policies IN (0, max_policies)
ORDER BY number_of_policies DESC;