如何将两个计数查询组合到它们的比例?

时间:2011-03-28 17:49:48

标签: mysql database

我有两个问题:

select count(*) from my_table where status="accepted"

select count(*) from my_table where status="rejected"

我要找到接受/拒绝的比例,所以我想知道是否可以组合这两个查询,所以我不必执行两个查询

5 个答案:

答案 0 :(得分:5)

因为到目前为止没有提供这个答案是正确的

select count(case when status = "accepted" then 1 end) /
       count(case when status = "rejected" then 1 end) as Ratio
from my_table
where status in ("accepted","rejected")

如果您还需要个人计数

select count(case when status = "accepted" then 1 end) Accepted,
       count(case when status = "rejected" then 1 end) Rejected,
       count(case when status = "accepted" then 1 end) /
       count(case when status = "rejected" then 1 end) as Ratio
from my_table
where status in ("accepted","rejected")

注意:MySQL没有除零问题。当Rejected为0时返回NULL。

答案 1 :(得分:2)

select accepted_count, rejected_count, accepted_count/rejected_count ratio
from (
    select sum(CASE WHEN status="accepted" THEN 1 ELSE 0 END) accepted_count,
           sum(CASE WHEN status="rejected" THEN 1 ELSE 0 END) rejected_count
    from my_table 
    ) A

答案 2 :(得分:1)

我认为这会奏效:

SELECT (Select count(*) from my_table where status="accepted") / (select count(*) from my_table where status="rejected") AS ratio

答案 3 :(得分:1)

select status, count(*) from my_table 
where status in ("rejected", "accepted")
group by status;

答案 4 :(得分:0)

select sum(case when status='accepted' then 1 else 0 end) as AcceptedCount,
       sum(case when status='rejected' then 1 else 0 end) as RejectedCount
    from my_table