我有一个如下例所示的表格。我想运行一个查询来显示 isActive=1 AND isNew=1、isActive=1 AND isOld=1 的总行数(所有 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
最佳答案
您可以在字段部分进行计数:
select sum((customer = 1) AND (isactive = 1) AND (isnew = 1)) etc...
from ...
MySQL 会默默地将 foo = bar AND baz=qux
测试的 bool 结果转换为整数 0
/1
,然后将它们相加向上。
关于MySQL 查询给出具有不同值组合的结果计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26538103/