使用group by和count in sql后如何使用count?

How to use count after using group by and count in sql?

我想查看有多少乘客从我的应用程序中通过的统计信息。选择此查询后;

select count(person_id), person_id from Passenger group by person_id;

count(person_id)    person_id
6                  123
2                  421
1                  542
3                  612
1                  643
2                  876

我看到乘客“123”通过了6次。 “421”通过了 2 次。 “542”通过了1次等等。所以我想分析一下;

>     1 passenger passed 6 times,
>     2 passenger passed 2 times,
>     2 passenger passed 1 times,
>     1 passenger passed 3 times..

这里sqlFiddle让你更好的理解..

select cnt, count(person_id)
from
(
  select count(person_id) as cnt, person_id 
  from Passenger 
  group by person_id
) tmp
group by cnt

您可以使用带有子查询的 SELECT 来获得您想要的结果:

SELECT Concat(COUNT(*), ' passenger passed ', table.theCount, ' times,') FROM
(
    SELECT COUNT(person_id) AS theCount, person_id
    FROM Passenger
    GROUP BY person_id
) table
GROUP BY table.theCount

这是您要找的吗?

select count(person_id) as "Num passengers", times
from (
  select count(person_id) as times, person_id
from Passenger 
group by person_id
) sub
group by times order by times ASC