How to add specific condition inside COUNT() in sql while doing a group by?

aroma :

Let's say I have a mysql table which has information about various tasks. The table looks like :

TASK_ID | TASK_INFO

task_1  | succeded
task_1  | failed
task_1  | failed
task_2  | succeded
task_2  | succeded
task_2  | failed

I want to calculate for each task the percentage of time it succeeded. for example the result for above table :

task1 | 33.3
task2 | 66.6

I was thinking of doing it in 2 steps, first calculate an intermediate table which has information about the number of runs for each task and another table for number of successes for each task.

Now it's straightforward to calculate the intermediate table with total runs for each task, but I'm not able to create a table which has number of successes for each task.

How do I do that?

Gordon Linoff :

You can use avg():

select task_id, avg( task_info = 'succeeded' ) as success_rate
from t
group by task_id;

If you prefer a number between 0 and 100 instead of between 0 and 1, multiply the value by 100.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=371640&siteId=1