在SQL中,在查询了某个列的COUNT之后,如何编写查询来确定该列中某个值的百分比

  • 本文关键字:查询 百分比 SQL COUNT 之后 何编写 mysql sql
  • 更新时间 :
  • 英文 :


这是我的代码:

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值与所有值的比值。

注意:这将忽略actionNULL值。使用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是小数后的数字

最新更新