Is there a function to handle "group by count of groups" (Group by aggregate) in one query?

Viewed 32

I keep getting questions about distributions (How many X did Y Z times?) and I have a fairly standard query that I use for this:

SELECT 
  Count(batter) AS count_batters,
  number_of_home_runs
FROM (
  SELECT
    batter, 
    COUNT(home_runs) as number_of_home_runs
  FROM
    baseball
  GROUP BY batter
)
GROUP BY number_of_home_runs

This would give a table of results like:

| count_batters | number_of_home_runs |   
| 1             | 1000                |   
| 2             | 800                 |  
| ...           | ...                 |  
| 65535         | 5                   |  

However, I want to know if there is a more elegant way to do this. Perhaps a way that doesn't use subqueries.

Also, I suspect this is a pattern (or anti-pattern) but can't figure out what its name might be; Any help on that would be appreciated.

FWIW, I'm working in AWS Redshift (like Postgres, but with differences); I'd like to hear solutions for other flavors as well, though!

0 Answers
Related