如何计算一组返回的组数?

时间:2012-02-10 16:48:03

标签: mysql count group-by

select count(*) as count from table
group by foreign_id order by count 

这将返回每个外部ID的多个匹配项。然而,我正在寻找的是总结结果。

结果将是:

10 results grouping 1 elements
5  results grouping 2 elements
7  results grouping 7 elements

2 个答案:

答案 0 :(得分:13)

好的,明白了。问题的标题比问题本身更好地表达了它:)

您需要先了解每个FK出现的次数:

select count(*) as GroupAmount from t1
group by foreign_id

一旦你有这个,你必须将它们分组以获得每个项目出现的次数与上面相同。这将导致:

select GroupAmount, count(*) GroupAmountTimes from (
  select count(foreign_id) as GroupAmount from t1
  group by foreign_id
) as SubQuery
group by GroupAmount

在行动here

中查看

答案 1 :(得分:5)

按组计算群组返回的群组数量:

select foreign_id as GroupAmount, count(foreign_id) as GroupAmountTimes
from t1
group by foreign_id

http://sqlfiddle.com/#!2/35661/42