在mysql范围内缺少缺失值

时间:2015-11-05 10:20:49

标签: mysql gaps-and-islands week-number

我已经问了一个类似的问题,但我似乎仍然无法理解它。我的sql数据库上有一个device_create_date列

2015-07-14 12:35:19
2015-07-15 12:45:37
2015-07-15 12:45:37
2015-07-16 12:35:37
2015-08-14 10:35:21
2015-08-14 12:15:36

我在几周内汇总了这些日期值,但是在几周之间存在缺失值,我希望这些值等于0,以便我可以将它们与excel表中的其他指标进行对比。我创建了一个虚拟表" date"连接值,以便select在几周内返回0,没有值。

这是我使用的查询,

select date.year, week(device.device_create_date), count(*)
from device 
join date
on date.week_of_year=week(device.device_create_date)
where device.id_customer = 1
group by device.year, date.WEEK_OF_YEAR
order by device.year, date.week_of_year;

这是我回来的,

2010    26  7252
2010    31  3108
2010    45  7203
2010    1   9324
2010    2   7252
2010    3   2072

这就是我想要它给我的东西;

2010 1  9324
2010 2  7252
2010 3  2072
2010 4  0
2010 5  0
2010 6  0 
etc

顺便说一下,这些数字似乎与数据库中的数量相匹配,所以我知道我做的事情完全错了,但我不是很擅长,所以任何帮助和方向都会很大赞赏。

提前谢谢!!

1 个答案:

答案 0 :(得分:1)

由于您始终需要date表中的值(以获取所有可能的日期)以及来自device的匹配行,因此您需要使用date作为来源并使用带有left join表的device,因为inner join只会返回两个表中匹配的数据。

请改为尝试:

select date.year, date.week_of_year, count(device.device_create_date) 
from date
left join device on date.week_of_year = week(device.device_create_date) 
                and device.id_customer = 1
group by date.year, date.week_of_year
order by date.year, date.week_of_year;

如果您的表包含超过一年的数据,您应该将年份的条件添加到联接中,这样您就不会混合多年的数据。

相关问题