colby_schrauth
colby_schrauth

Reputation: 41

MySQL - WHERE statement only applies to a portion of the SELECT statement

I want to divide a COUNT statement by a SUM statement, with a WHERE statement that only applies to the COUNT statement.

Here is an example table:

id     eligible     not_eligible     call

1         0            1               1
2         1            0               1
3         1            0               1

My goal:
SELECT COUNT(ID) / SUM(Call)
FROM my_table
WHERE not_eligible = 1

I want the WHERE statement to only apply to the COUNT statement. I want to return 1/3 (33%), instead of 1/1 (100%). Any idea how I can make a WHERE statement apply to only a portion of my SELECT statement?

Upvotes: 1

Views: 49

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64496

In Mysql you can use the condition in sum function to get your desired count ,sum with condition will result as boolean 0 or 1 and you can have your count based on different conditions,Also you are using an aggregate function but with out grouping them i.e(group by somecol) so this will apply to whole table and considered as one group

SELECT SUM(not_eligible = 1) / SUM(`Call`) 
FROM my_table 

Demo

Upvotes: 2

Related Questions