MySQL查询以给出具有不同值组合的结果计数

时间:2014-10-23 21:53:17

标签: mysql

我有一个类似下面例子的表格。我想运行一个查询来显示总行数,其中isActive = 1 AND isNew = 1,isActive = 1 AND isOld = 1 all customerID = 1

orderID customerID  isActive    isNew   isOld
1       1           1           0       1
2       1           0           0       1
3       1           1           0       0
4       1           1           1       1
5       2           1           0       1
6       2           0           0       1
7       2           1           0       0
8       2           1           1       1

我知道我可以查询:

select count(*) from table where customer=1 and isActive=1 and isNew=1

但这只是给了我一个条件的总和,我想在一个查询中做两个条件。

类似的东西:

select count1, count2 from table where (customer=1 and isActive=1 and isNew=1) as count1, (customer=1 and isActive=1 and isOld=1) as count2

1 个答案:

答案 0 :(得分:1)

您可以在字段中进行计数:

select sum((customer = 1) AND (isactive = 1) AND (isnew = 1)) etc...
from ...

MySQL会默默地将foo = bar AND baz=qux测试的布尔结果转换为整数0 / 1,然后将它们相加。