2012-02-10 56 views
6
select count(*) as count from table 
group by foreign_id order by count 

這將爲每個外部標識返回一些匹配項。然而,我要找的是總結結果。如何統計組返回的組數量?

那麼結果將是:

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

請解釋一下你的意思通過「_n_結果分組_n_元素」什麼是分組? – 2012-02-10 16:50:20

+1

我不太明白'5個結果分組2個元素'。 '5'和'2'代表什麼? – 2012-02-10 17:02:18

+1

它很難解釋。目前如果它匹配了外鍵,那麼它會說1個匹配,然後它會移動到下一個,並說1匹配,然後兩個匹配另一個匹配。我想要做的是確定找到1次比賽的次數。或者找到3場比賽的次數。 – 2012-02-10 17:34:20

回答

11

好,知道了。問題的標題expainls比問題本身:)

首先,您需要知道每個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

鏈接到sqlfiddle停止工作:( – Shai 2015-04-29 10:53:31

4

由數由一組返回組數:

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

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