简体   繁体   English

SQL:按计数(*)分组为总表行数的pct

[英]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. 我使用的数据库是Postgres语法兼容的,并且表上的count(*)非常快,所以在表上执行count(*)没有大的速度命中,尽管我想写更好的SQL,如果有的话可能。

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: 由于PostgreSQL支持窗口函数,你可以这样做:

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. 您还可以将表上的count(*)作为单独的查询执行,然后将其与原始查询一起连接到SELECT语句的FROM部分。 That should be quicker than putting it in the SELECT part. 这应该比把它放在SELECT部分​​更快。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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