简体   繁体   English

在 SQL 中计算百分比

[英]Calculating Percentages in SQL

I am trying to return the % of a record's value in a field, where the field is created by using GROUP BY and COUNT like this:我正在尝试返回字段中记录值的百分比,该字段是通过使用 GROUP BY 和 COUNT 创建的,如下所示:

SELECT col_1, COUNT(col_2)
FROM table_name
GROUP BY col_1
ORDER BY 2;

So, this code gives us something like:所以,这段代码给了我们类似的东西:

col_1.  |.  col_2
A       |  5
B       |  10
C       |  5
...

What I'd like is to write a query that would then give me:我想要的是写一个查询,然后给我:

col_1.  |.  col_2
A       |  .25
B       |  .50
C       |  .25
...

How can I use what I originally created in order to get this sort of output?我如何使用我最初创建的内容来获得这种输出? I've tried to use something like this but it doesn't work:我试过使用这样的东西,但它不起作用:

SELECT col_1, COUNT(col_2) / SUM(col_2)
FROM table_name
GROUP BY col_1
ORDER BY 2;

Thank you for any help you can offer!感谢您提供的任何帮助!

Just use a window function:只需使用窗口函数:

SELECT col_1, COUNT(col_2),
       COUNT(col_2) * 1.0 / SUM(COUNT(col_2)) OVER ()
FROM table_name
GROUP BY col_1
ORDER BY 2;

Note: I added the * 1.0 .注意:我添加了* 1.0 You don't specify the database you are using and some do integer division (so 1 / 2 is 0 rather than 0.5 ).你没有指定你正在使用的数据库,有些人做整数除法(所以1 / 20而不是0.5 )。

You can always do:你总是可以这样做:

SELECT
  col_1, 
  1.0 * COUNT(col_2) / (select sum(col_2) from table_name)
FROM table_name
GROUP BY col_1
ORDER BY 2;

The issue is that in SQL, when you want to count total, its an aggregate function and the individual rows will be "lost".问题是在 SQL 中,当您想计算总数时,它是一个聚合函数,并且各个行将“丢失”。

One way is to use "window function" if you are on MS SQL newer versions.如果您使用的是 MS SQL 较新版本,则一种方法是使用“窗口函数”。

Another way build the total as another table (example below totalTable), and then cross apply to join the original table with this new table.另一种方法将总数构建为另一个表(在 totalTable 下的示例),然后交叉应用以将原始表与这个新表连接起来。 Then you are use the "total" column.然后您将使用“总计”列。 Something like below.像下面这样的东西。

SELECT col_1, COUNT(col_2) / total as percentage
FROM table_name
    CROSS APPLY 
        ( SELECT COUNT(*) as total from table_name ) totalTable
        )
GROUP BY col_1, total

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

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