如何在不使用聚合函数的情况下进行限制

How to restrict by an aggregate function without using it

假设我有一个像这样的 table(是的,我是一个 Trekkie)...

CREATE TABLE starship_first_contacts (
  first_contact_id ID,
  starship_code CHAR,
  first_contact_species VARCHAR (40),
  first_contact_date DATE);

而且我想看看有多少艘船进行了 10 次以上的首次接触,所以我写了一个 SQL 这样的..

select count(*), 
       starship_code
from starship_first_contacts 
group by starship_code
having count (*) > 10

但如果我想看看那些首次接触超过 10 次的飞船是什么,SQL 会是什么样子?

理想情况下,我希望在结果集中列出 starship_codes 以及他们各自进行了多少次首次接触,并且只想要超过 10 次的接触。

how many ships have made over 10 first contacts

select count(*)
from (select starship_code
    from starship_first_contacts 
    group by starship_code
    having count (*) > 10
    ) as active

what are those ships with over 10 first contacts

select starship_code
from starship_first_contacts 
group by starship_code
having count (*) > 10

请注意,第一个使用第二个。似乎您认为您必须根据第一个查询来编写第二个查询,但事实恰恰相反。

Ideally in the result set I would like a list of starship_codes and how many first contacts they each made and only want those which made over 10.

这就是你现在问题中的查询:

select count(*), 
       starship_code
from starship_first_contacts 
group by starship_code
having count (*) > 10

"I want to see how many ships have made over 10 first contacts, so I write a SQL like this" 的正确答案可能是这样的。

select count(*)
From (
  Select
   starship_code
  from starship_first_contacts 
  group by starship_code
  having count (*) > 10
) d

但是,您第二个问题的答案是您发布的 SQL

select count(*), 
   starship_code
from starship_first_contacts 
group by starship_code
having count (*) > 10