Mysql在计数时获取零值

时间:2017-06-28 14:51:44

标签: mysql sql syntax count

我试图计算一段时间内已取消的销售订单数量。但我遇到的问题是它没有返回零结果

我的表

+---------------+------------+------------------+
| metrausername | signupdate | cancellationdate |
+---------------+------------+------------------+
| GLO00026      | 2017-06-22 | 2017-03-20       |
| GLO00055      | 2017-06-22 | 2017-04-18       |
| GLO00022      | 2017-06-27 | NULL             |
| GLO00044      | 2017-06-24 | NULL             |
| GLO00005      | 2017-06-26 | NULL             |
+---------------+------------+------------------+

我试图用

计算的声明
SELECT metrausername, COUNT(*) AS count FROM salesdata2 
WHERE cancellationdate IS NOT NULL 
AND signupDate >= '2017-6-21' AND signupDate <= '2017-7-20' 
GROUP BY metrausername;

如果有任何其他信息有帮助,请告诉我

2 个答案:

答案 0 :(得分:1)

如果metrausername被where过滤掉,它将不会出现。左连接到聚合以解决此问题:

select distinct a1.metrausername, coalesce(a2.counted,0) as counted -- coalesce replaces null with a value
from salesdata2  a1
left join
(
SELECT metrausername, COUNT(*) AS counted
FROM salesdata2 
WHERE cancellationdate IS NOT NULL 
AND signupDate >= '2017-6-21' AND signupDate <= '2017-7-20' 
GROUP BY metrausername
) a2
on a1.metrausername = a2.metrausername

答案 1 :(得分:1)

我只是将过滤子句移到select。假设你真的想要日期范围(而不是让用户超出范围),那么:

SELECT metrausername, COUNT(cancellationdate ) AS count
FROM salesdata2 
WHERE signupDate >= '2017-06-21' AND signupDate <= '2017-07-20' 
GROUP BY metrausername;

COUNT(<colname>)计算非NULL值,因此这似乎是最简单的方法。