Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two count queries to their ratio?

Tags:

database

mysql

I have two queries:

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

and

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

I was to find the ratio of accepted/reject so I Was wondering if it's possible to combine the two queries so I don't have to execute two queries

like image 882
Tam Avatar asked Mar 28 '11 17:03

Tam


2 Answers

Putting this answer since none offered so far is correct

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")

If you also need the individual counts

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")

Note: MySQL does not have a divide by zero problem. It returns NULL when Rejected is 0.

like image 132
RichardTheKiwi Avatar answered Sep 23 '22 03:09

RichardTheKiwi


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
like image 21
manji Avatar answered Sep 20 '22 03:09

manji