使用 GROUP BY 时包括缺失的(零计数)行 [英] including missing (zero-count) rows when using GROUP BY

查看:23
本文介绍了使用 GROUP BY 时包括缺失的(零计数)行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接收短信的应用程序.我想要做的是用 mysql 做一个统计,它会在一小时内计算消息.例如,早上 7 点我收到 10 条短信,早上 8 点我收到 20 条等等.我的表有这个列 ID、smsText、smsDate ...(其他不重要).当我运行这个脚本时:

I have an application that receives sms messages. What i want to do is make a statistic with mysql that will count meessages in a hour. For example in 7 am i received 10 sms messages, in 8 am i received 20 etc. My table has this columns ID, smsText, smsDate ... (others are not important). When i run this script:

SELECT HOUR(smsDate), COUNT(ID) FROM SMS_MESSAGES GROUP BY HOUR(smsDate)

它显示我每小时收到多少条消息.问题是当我没有收到任何消息时,例如在下午 5 点,此语句不会返回计数为 0 的第 17 行,结果如下:

it show how many messages i get in every hour. The problem is when i dont receive any message for example in 5pm, this statement does't return a row 17 with count 0, and i have a result like this:

Hour Count
...
15 10
16 5
18 2
...

,而我想要的是这个

Hour Count
...
15 10
16 5
17 0
18 2
...

我在网上搜索了一个解决方案,使用 UNION 的方法,但我不明白如何在我的系统中实现该解决方案.希望有人能帮助我.

I searched for a solution on the web, something with UNION but i don't understand how to implement that one in mine. Hope someone can help me.

推荐答案

您可以创建一个包含所有小时的表并加入这些表:

You could create a table with all hours and join the tables:

CREATE TABLE IF NOT EXISTS `hours` (
  `hour` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `hours` (`hour`) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12), (13), (14), (15), (16), (17), (18), (19), (20), (21), (22), (23);

SELECT hours.hour, count( SMS_MESSAGES.ID ) 
FROM hours
LEFT JOIN SMS_MESSAGES ON ( hours.hour = HOUR( SMS_MESSAGES.smsDate ) ) 
GROUP BY 1 

这篇关于使用 GROUP BY 时包括缺失的(零计数)行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆