这是我的代码:
SELECT
COUNT(Action_taken)
FROM
Friend_requests
WHERE action_taken = “Accepted”
--我如何编写第二个查询来确定等于"0"的值的百分比;接受";?
最简单的方法是条件聚合。在MySQL中,您可以将其表示为:
select avg(action = 'accepted')
from friend_requests;
这是因为MySQL将布尔值视为true
的1,将0
视为false。因此,平均值是true
值与所有值的比值。
注意:这将忽略action
的NULL
值。使用NULL
安全比较运算符可以轻松处理这一问题
select avg(action <=> 'accepted')
from friend_requests;
select
(select count(1) from friend_requests where action = "accepted")
/
(select count(1) from friend_requests)
作为@Gordon Linoff的回答和@Strawberry的评论,对我来说,ful查询有点像:
select round(avg(action = 'accepted') * 100, x)
from friend_requests
where action_taken is not null
- x是小数后的数字