我在为具有不同 where 子句的列的多个不同计数创建最有效的查询时遇到问题。我的 MYSQL 表如下所示:
id client_id result timestamp
---------------------------------------------------
1 1234566 escalated 2014-01-02 00:00:00
2 1233344 approved 2014-02-03 00:00:00
3 1234566 escalated 2014-01-02 01:00:00
我想要实现的是在返回中构建以下数据:
从开始时处理的唯一客户端 ID 总数。
处理的唯一客户端 ID 总数从一开始就不断增加。
从一开始就批准处理的唯一客户端 ID 总数。
使用时间戳上的语句之间在指定时间范围内批准的唯一客户端 ID 的计数。
使用时间戳上的语句在指定时间范围内升级的唯一客户端 ID 计数。
我考虑过运行多个选择,但我认为这会浪费资源,如果这可以通过单个查询来完成,这可能是处理它的最佳方法,不幸的是我在这方面缺乏经验。我希望返回 simple 包含别名和计数。
如有任何帮助,我们将不胜感激。
最佳答案
您想要条件聚合,例如:
select count(distinct ClientId) as NumClients,
count(distinct case when result = 'Approved' then ClientId end) as NumApproved,
count(distinct case when result = 'Escalated' then ClientId end) as NumEscalated,
count(distinct case when result = 'Approved' and timestamp between @Time1 and @Time2
then ClientId end) as NumApproved,
count(distinct case when result = 'Escalated' and timestamp between @Time1 and @Time2
then ClientId end) as NumEscalated,
from table t;
关于mysql - 多个不同的计数与 where,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24454616/