我的表就像:
+---------+---------+------------+-----------------------+---------------------+
| 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 |
+---------+---------+------------+-----------------------+---------------------+
记录访客的轨迹以及对所访问地点的一些评论。
我想计算从0:00到23:59,在某个时间间隔(即30分钟)内访问特定地点(比如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到该位置访问03:00,这不会给我02:00-02:29和02:30-2:59的间隔。
我想要一个精确大小为48 的结果(每半小时一个),我该怎么做?
答案 0 :(得分:2)
您必须创建一个包含所需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