这是我的问题: 我有一个表有一些记录,如(名称,日期,类型)。假设我有三个类型a,b和c。现在我想将每个类型计为type_count但有一些限制并使用count(a)/ count(b)进行除法以得到百分比结果,并且a和a中的限制是不同,我该怎么处理?谢谢!我的代码看起来像这样:
SELECT name, count(a), count(a)/count(b)
from table
where ...
是否可以在select中创建一些子查询?看起来像这样
select name, count(a), count(a)/ (select count(b) from table where restriction_for_b)
from table
where retriction_for_a
答案 0 :(得分:10)
如果我正确理解您的问题,您可以使用sum(if(condition, 1, 0))
替换计数。像这样:
select
name,
sum(if(condition_for_a, 1, 0)),
sum(if(condition_for_a, 1, 0)) / sum(if(condition_for_b, 1, 0))
from table
where ...