从visitlogs表计算每小时的访问量

时间:2013-03-20 12:27:37

标签: mysql

我有一张桌子记录了一些地点的一些访问信息以及时间,也许对这个地方有一些评论,如:

+---------+---------+------------+-----------------------+---------------------+
| visitId | userId  | locationId | comments              | time                |
+---------+---------+------------+-----------------------+---------------------+
|       1 |    3    |     12     | It's a good day here! | 2012-12-12 20:50:12 |
+---------+---------+------------+-----------------------+---------------------+

我要做的是按小时计算访问量,我希望以这种方式生成结果:

+------------+-----+-----+-----+-----+-----+-----+-------+------+
| locationId |  0  |  1  |  2  |  3  |  4  |  5  |  ...  |  23  |
+------------+-----+-----+-----+-----+-----+-----+-------+------+
|      12    |  15 |  12 |  34 |  67 |  78 |  89 |  ...  |  34  | 
+------------+-----+-----+-----+-----+-----+-----+-------+------+

我该怎么做? 我想评估一整天的访问差异。

3 个答案:

答案 0 :(得分:1)

这将为您提供每个locationid的小时访问次数

SELECT locationId, HOUR(time), COUNT(*)
FROM table
GROUP BY locationId, HOUR(time)

答案 1 :(得分:1)

如果不进行测试,我认为这样可行:

select locationid, hour(time) as hour, count(distinct userid) as usercnt
from table_1
group by locationid, hour;

它不会按照你的建议进行调换,但数据是相同的

答案 2 :(得分:1)

尝试使用下面的查询:

SELECT  location_id, sum(case when HOUR(time) = 0 then 1 else 0) as '0', 
        sum(case when HOUR(time) = 1 then 1 else 0) as '1',-- till 23
FROM table
GROUP BY location_id