mysql 中的计数缺失值

Missing values on count in mysql

我只是被 atm 问题困住了,我不是 100% 确定如何处理它。

我有一个 table 每周汇总数据的地方

 select week(create_date),count(*) 
from user 
where create_date > '2015-02-01'
and id_customer between 9 and 17
group by week(create_date);

我得到的结果在计数中有缺失值,如下所示

5   334
6   376
7   394
8   405
9   504
10  569
11  709
12  679
13  802
14  936
15  1081
16  559
21  1
24  9
25  22
26  1
32  3
34  1
35  1

例如,这里从 16 到 21 显然缺少 4 个值我希望将这些值包括在内并计数为 0。我想要这个是因为我希望周数与我们输出的其他指标相匹配他们在 excel 文件中进行内部分析。

如有任何帮助,我们将不胜感激。

问题是没有符合您的缺失周标准的数据。一种解决方案是从具有所有周数的 table 加入。例如,如果你创建一个 table weeknumbers,其中一个字段 weeknumber 包含从 0 到 53 的所有数字,你可以使用这样的东西

select weeknumber,count(user.*) 
from weeknumbers left join user on (weeknumbers.weeknumber=week(user.create_date) 
and user.create_date > '2015-02-01'
and user.id_customer between 9 and 17)
group by weeknumber;

此外,您可能希望限制不想看到的周数。 另一种方法是在应用程序中进行。

问题是 sql 查询无法真正生成根本不存在的数据。

您有 3 个选项:

  1. 如果您在查询期间的整个 table 中每个星期都有数据,那么您可以使用自连接来获取缺失的星期:

    select week(t1.create_date), count(t2.id_customer) from customer t1 left join customer t2 on t1.id_customer=t2.id_customer and t1.create_date=t2.create_date and t2.id_customer between 9 and 17 where t1.create_date > '2015-02-01' group by week(t1.create_date)

  2. 如果您缺少来自客户 table 的整个周数,则创建一个助手 table,其中包含从 1 或 0 开始的周数(取决于 mysql config) 到 53 并做一个左连接到这个助手 table.

  3. 使用存储过程循环遍历原始查询的结果,并使用临时 table 然后 returns 扩展数据集将缺失数据插入结果集中结果.