0

我的桌子是这样的:

+---------+---------+------------+-----------------------+---------------------+
| 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 的结果(每半小时一个),我该怎么做?

4

1 回答 1

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
于 2013-03-27T01:38:47.300 回答