简体   繁体   English

在执行分组时如何在 COUNT() 中的 sql 中添加特定条件?

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

Let's say I have a mysql table which has information about various tasks.假设我有一个 mysql 表,其中包含有关各种任务的信息。 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?我怎么做?

You can use avg() :您可以使用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.如果您更喜欢 0 到 100 之间的数字而不是 0 到 1 之间的数字,请将值乘以 100。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM