使用 GROUP BY 时包括缺失的(零计数)行

2021-12-30 00:00:00 group-by count mysql aggregate-functions

我有一个接收短信的应用程序.我想要做的是用 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 

相关文章