2015-11-03 91 views
2

我只是坚持这个问题atm,我不是100%确定如何处理它。在mysql中的计数值缺失

我在那里我汇总数据上一周

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文件中进行内部分析。

任何帮助将不胜感激。

回答

1

问题是,sql查询不能真正产生根本就没有的数据。

你有3种选择:

  1. 如果你在你所查询期间整个表中的每个星期的数据,那么你可以使用一个自连接得到缺少周:

    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. 如果从客户表作为一个整体有缺失周,然后创建一个包含周数从1或0(取决于MySQL的配置),以53的辅助表,做一个左连接到这个辅助表。

  3. 使用循环遍历原始查询结果的存储过程,并使用临时表在结果集中插入缺失的数据,然后返回扩展数据集作为结果。

+0

这是一个非常透彻的解释,从这里我很直观,我认为,因为有价值缺失,我会继续前进,并创建帮助表你建议,它应该采取一个方向,然后。再次感谢你,非常感谢。 –

+0

如果第一天失踪,即第一周恰好为5,那么最好的解决方案是什么,以便从第一周开始? –

+0

我不明白你的问题。第一天从哪里失踪?你想从哪里开始:第1周还是第5周? – Shadow

1

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

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; 

Additionaly你可能想限制你不希望看到的周数。 另一种方法是在应用程序中执行此操作。

+0

非常感谢,我有点考虑通过案头研究的选择,但我现在有一个更好的方向。 #thumbsup –