gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:23:19 25 4
gpt4 key购买 nike

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

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

    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 

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

最佳答案

您可以使用AVG():

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

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

SELECT AVG(CASE WHEN status = 'Pending' THEN 1.0 ELSE 0 END)

关于mysql - SQL-计算多个计数的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59213505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com