2013-03-27 86 views
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 | 
+---------+---------+------------+-----------------------+---------------------+ 

它记录游客的轨迹和对地的一些意见参观

我想算在访问一个特定的地方游客数量(ID说3227 =)从0:00到23:59,在几个间隔(即30分钟)

我试图做这由:

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

+1

@Rono感谢您的帮助! – zoujyjs 2013-03-27 01:32:45

回答

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 
+0

这个工作,但它是痛苦输入这么长的声明..谢谢! – zoujyjs 2013-03-27 01:46:48