简体   繁体   中英

SQL: Group by count(*) as pct of total table row count

I've spent a lot of time searching for this, please let me know if duplicate.

I need to write a grouped query that returns the categories of records with the count of each type of category. Something like this:

select categorynum, count(*) from tbl group by categorynum;

So far so good. Now what I need is to determine what % of the total each category's count occupies. The best I have come up with is this, which I do not like, it feels dirty:

select categorynum, count(*), count(*)/(select count(*) from tbl) from tbl group by categorynum;

It works, but it's really nagging me to do it this way. The database I use is Postgres syntax compatible, and count(*) on a table is really fast, so there is no huge speed hit for doing a count(*) on the table, though I would like to write better SQL if at all possible.

So is there a better way to write this? This is a situation I run into often, so I would like to write my queries correctly.

Since PostgreSQL supports window functions, you could do something like this:

select categorynum,count,100*count/(sum(count) over ())::numeric as count_pct
from(
    select categorynum,count(1)
    from tbl
    group by categorynum
)a;

You can also do the count(*) on the table as a separate query and then join that with your original query in the FROM portion of your SELECT statement. That should be quicker than putting it in the SELECT part.

select categorynum, categorycount, total
from (select categorynum, count(*) as categorycount
      from tbl
      group by categorynum) categories,
     (select count(*) as total from tbl) totals

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM