Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of groups returned by a group by?

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

This returns a number of matches for each foreign id. However what im looking for is to summarise the results.

So the result would be:

10 results grouping 1 elements
5  results grouping 2 elements
7  results grouping 7 elements
like image 953
Robbo_UK Avatar asked Feb 10 '12 16:02

Robbo_UK


People also ask

How do I count the number of groups after a group in SQL?

SQL – count() with Group By clause The count() function is an aggregate function use to find the count of the rows that satisfy the fixed conditions. The count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.

Can we use count with GROUP BY?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

How do I count rows in a GROUP BY?

To count the number of rows, use the id column which stores unique values (in our example we use COUNT(id) ). Next, use the GROUP BY clause to group records according to columns (the GROUP BY category above). After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause.


2 Answers

Ok, got it. The title of the question expainls it better than the question itself :)

You need to first know how many times each FK appears:

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

Once you have this, you have to group them to get the amount of times each item appears the same way as above. This will result in:

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

See it in action here

like image 112
Mosty Mostacho Avatar answered Sep 22 '22 10:09

Mosty Mostacho


Count the number of groups returned by a group by:

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

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

like image 23
Susmita Mitra Avatar answered Sep 25 '22 10:09

Susmita Mitra