SQL - 计算计数百分比(列)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37303779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:36:26  来源:igfitidea点击:

SQL - Calculate percentage on count(column)

sqlpercentagecalculated-field

提问by Dean Flaherty

I have the following piece of code which counts how many times something appears in the event column.

我有以下一段代码,它计算事件列中出现的次数。

SELECT event, count(event) as event_count   
FROM event_information
group by event

event   event_count
a       34
b       256
c       45
d       117
e       3

I want to be able to calculate the percentage of each of the rows like so.

我希望能够像这样计算每一行的百分比。

event   event_count event_percent
a       34          7.47
b       256         56.26
c       45          9.89
d       117         25.71
e       3           0.66

回答by juergen d

SELECT event, 
       count(event) as event_count,
       count(event) * 100.0 / (select count(*) from event_information) as event_percent
FROM event_information
group by event

回答by Gordon Linoff

Most SQL dialects support ANSI standard window functions. So, you can write the query as:

大多数 SQL 方言都支持 ANSI 标准窗口函数。因此,您可以将查询编写为:

select event, count(*) as event_count,
       count(*) * 100.0/ sum(count(*)) over () as event_percent
from event_information
group by event;

Window functions are generally more efficient than subqueries and other methods.

窗口函数通常比子查询和其他方法更有效。