在给定单个 DATETIME 字段的情况下,发现了几种按小时分组的解决方案。在我的例子中,我有一个 DATETIME 范围,我需要将结果按小时分组并获取计数。
我将尝试在下面说明我的表结构。我的数据表如下。
mysql> select * from access_logger;
+---------+---------------------+---------------------+
| user_id | entered_at | exit_at |
+---------+---------------------+---------------------+
| 20178 | 2017-09-11 07:02:35 | 2017-09-11 10:10:09 |
| 18998 | 2017-09-11 08:02:35 | 2017-09-11 08:41:45 |
| 6754 | 2017-09-11 08:02:35 | 2017-09-11 12:06:42 |
| 18998 | 2017-09-11 09:02:35 | 2017-09-11 13:30:43 |
| // results continues.... |
+---------+---------------------+---------------------+
根据上面的表结构我想看看每小时有多少用户连接到系统。预期的结果就像...
+------+-------+
|hours | count |
+------+-------+
| 7 | 1 |
| 8 | 2 |
| 9 | 3 |
| 10 | 3 |
| 11 | 2 |
| 12 | 2 |
| 13 | 1 |
+------+--------
我创建了一个独立获取每小时结果的查询。
mysql> select "10" as hours, count(user_id) as count
-> from access_logger
-> where hour(entered_at) <=10 and hour(exit_at) >= 10;
+------+-------+
|hours | count |
+------+-------+
| 10 | 3 |
+------+--------
上面的查询只会得到一个小时组的输出。我如何编写一个查询,在 24 行中创建所有 24 小时的输出?
最佳答案
如果您的表(或您的任何其他表)的行数超过 24 行,您可以合并查询和
SELECT @N := @N +1 AS hour
FROM access_logger , (SELECT @N:=-1) dum LIMIT 23;
发现于 SQL SELECT to get the first N positive integers
即
select a.hour, count(b.user_id) as count
from access_logger b inner join (SELECT @N := @N +1 AS hour
FROM access_logger , (SELECT @N:=-1) dum LIMIT 23) a on
hour(entered_at) <= a.hour and hour(exit_at) >= a.hour;
抱歉,手头没有mysql,所以没有测试
关于mysql - 在给定时间范围内按小时分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46510322/