我的 table 是这样的:
+---------+---------+------------+-----------------------+---------------------+
| visitId | userId | locationId | comments | time |
+---------+---------+------------+-----------------------+---------------------+
| 1 | 3 | 12 | It's a good day here! | 2012-12-12 11:50:12 |
+---------+---------+------------+-----------------------+---------------------+
| 2 | 3 | 23 | very beautiful | 2012-12-12 12:50:12 |
+---------+---------+------------+-----------------------+---------------------+
| 3 | 3 | 52 | nice | 2012-12-12 13:50:12 |
+---------+---------+------------+-----------------------+---------------------+
记录访问者的轨迹以及对所访问地点的一些评论。
我想统计在一定时间间隔(即 30 分钟)内从 0:00 到 23:59 访问特定地点(例如 id=3227)的访客数量
我试图通过以下方式做到这一点:
SELECT COUNT(*) FROM visits
GROUP BY HOUR(time), SIGN( MINUTE(time) - 30 )// if they are in the same interval this will yield the same result
WHERE locationId=3227
问题是如果没有记录落在某个时间间隔内,则不会返回计数为 0 的该时间间隔。例如,从 02:00 到 02:00 没有访客访问该位置03:00,这不会给我 02:00-02:29 和 02:30-2:59 的间隔。
我想要一个精确大小为 48 的结果(每半小时一个),我该怎么做?
最佳答案
您必须创建一个包含所需 48 行的表并使用左外连接:
select n.hr, n.hr, coalesce(v.cnt, 0) as cnt
from (select 0 as hr, -1 as sign union all
select 0, 1 union all
select 1, -1 union all
select 1, 1 union all
. . .
select 23, -1 union all
select 23, 1 union all
) left outer join
(SELECT HOUR(time) as hr, SIGN( MINUTE(time) - 30 ) as sign, COUNT(*) as cnt
FROM visits
WHERE locationId=3227
GROUP BY HOUR(time), SIGN( MINUTE(time) - 30 )
) v
on n.hr = v.hr and n.sign = v.sign
order by n.hr, n.hr
关于mysql - 计算间隔之间的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15650423/