Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL COUNT of COUNT

I have some data I am querying. The table is composed of two columns - a unique ID, and a value. I would like to count the number of times each unique value appears (which can easily be done with a COUNT and GROUP BY), but I then want to be able to count that. So, I would like to see how many items appear twice, three times, etc.

So for the following data (ID, val)...

1, 2
2, 2
3, 1
4, 2
5, 1
6, 7
7, 1

The intermediate step would be (val, count)...

1, 3
2, 3
7, 1

And I would like to have (count_from_above, new_count)...

3, 2 -- since three appears twice in the previous table
1, 1 -- since one appears once in the previous table

Is there any query which can do that? If it helps, I'm working with Postgres. Thanks!

like image 745
cryptic_star Avatar asked Nov 02 '25 11:11

cryptic_star


1 Answers

Try something like this:

select
   times,
   count(1)
from ( select 
          id,
          count(distinct value) as times
       from table
       group by id ) a
group by times
like image 54
Jose Chama Avatar answered Nov 04 '25 03:11

Jose Chama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!