SQL-计算多个计数的百分比

问题描述 投票:0回答:1

我写了一个查询来按状态对db中的所有项目进行计数和分组。

现在,我需要计算每个给定结果的百分比。

    SELECT 
      COUNT(CASE WHEN status='Pending' THEN 1 ELSE NULL END)  as 'Pennding Requests',
      COUNT(CASE WHEN status='Accepted' THEN 1 ELSE NULL END) as 'Accepted Requests',
      COUNT(CASE WHEN status='Denied' THEN 1 ELSE NULL END) as 'Denied Requests'
    FROM meeting_request;

给了我:

enter image description here

我尝试过类似的事情:

       100.0 * (id / Pennding Requests) AS PERCENTAGE 

有人可以建议如何计算这三种状态的百分比。

mysql sql percentage
1个回答
0
投票

您可以使用AVG()

SELECT AVG( status = 'Pending' )  as pending_requests,
       AVG( status = 'Accepted' ) as Accepted_Requests,
       AVG( status = 'Denied' ) as Denied_Requests
FROM meeting_request;

由于MySQL将布尔值解释为数字,其中1表示true,0表示false,因此可以使用方便的快捷方式。更正式的SQL代码是:

SELECT AVG(CASE WHEN status = 'Pending' THEN 1.0 ELSE 0 END)
© www.soinside.com 2019 - 2024. All rights reserved.