如何计算group by子句计数值中的计数数

时间:2014-09-26 13:18:14

标签: sql postgresql group-by

如何按分组结果计算计数结果

select count(*) 
from
( 
  select first_name,count(first_name) 
  from actor
  group by first_name
  having count(first_name) in (2,4) 
);

1 个答案:

答案 0 :(得分:1)

您缺少派生表的别名:

select count(*) 
from
( 
  select first_name,count(first_name) 
  from actor
  group by first_name
  having count(first_name) in (2,4) 
) as t ;               
   --^
   --|------------------------ alias "t"

查询也可以简化为:

select count(*) 
from
(                         -- the columns can be skipped, 
  select 1                -- as they are not needed in the upper level
  from actor 
  group by first_name
  having count(*) in (2,4) 
) as t ;  

或混淆为:

select distinct 
    count(case when count(*) in (2,4) then 1 end) over () 
from actor
group by first_name ;