MySql查询以按小时汇总的访问者数量

时间:2017-11-23 09:45:09

标签: mysql sql datetime aggregate

我有一个MySql表,其中的访问者数据显示访问者何时到达并离开,我正在尝试按时间汇总数据,以便我可以看到访问者的数量:

+----------+---------------------------+---------------------------+
|visitor   |entry_time                 |exit_time                  |
+----------+---------------------------+---------------------------+
|a         |2017-11-20 11:30:00        |2017-11-20 14:15           |
|b         |2017-11-20 10:30:00        |2017-11-20 11:20:00        |
|c         |2017-11-20 09:50:00        |2017-11-20 17:05:00        |
|d         |2017-11-20 10:00:00        |2017-11-20 13:25:00        |
|e         |2017-11-20 12:40:00        |2017-11-20 16:30:00        |
|f         |2017-11-20 13:20:00        |2017-11-20 15:20:00        |
+----------+---------------------------+---------------------------+

我想知道每小时的访客人数:

+-----------------------+-------------------+
|time_of_day            |number_of_visitors |
+-----------------------+-------------------+
|2017-11-20 08:00       |0                  |
|2017-11-20 09:00       |1                  |
|2017-11-20 10:00       |3                  |
|2017-11-20 11:00       |4                  |
|2017-11-20 12:00       |4                  |
|2017-11-20 13:00       |5                  |
|2017-11-20 14:00       |4                  |
|2017-11-20 15:00       |3                  |
|2017-11-20 16:00       |2                  |
|2017-11-20 17:00       |1                  |
+-----------------------+-------------------+

我可以创建一个查询,按小时计算出口或条目的数量:

SELECT
    str_to_date(date_format((`entry_time`),'%y-%M-%D %H:00:00'), '%Y-%M-%D %H:00:00') AS `time_of_day`,
    COUNT(DISTINCT `visitors`) AS `number_of_visitors`
FROM
    `tbl_visitors`  
GROUP BY 1

但是我无法创建一个查询来汇总当天任何时间(以及一周中任何一天)的访问者总数。

1 个答案:

答案 0 :(得分:0)

创建日历表

CREATE TABLE tbl_calendar_hours(
  hour_of_day datetime PRIMARY KEY
);

将所有必要日期(包括小时数)插入此表

INSERT tbl_calendar_hours(hour_of_day)VALUES
('2017-01-01 00:00'),
...
('2017-11-20 08:00'),
('2017-11-20 09:00'),
('2017-11-20 10:00'),
('2017-11-20 11:00'),
('2017-11-20 12:00'),
('2017-11-20 13:00'),
('2017-11-20 14:00'),
('2017-11-20 15:00'),
('2017-11-20 16:00'),
('2017-11-20 17:00'),
...
('2017-12-31 23:00');

在查询中使用它

SELECT
    h.hour_of_day,
    COUNT(DISTINCT v.visitor) AS number_of_visitors
FROM tbl_calendar_hours h
LEFT JOIN tbl_visitors v ON v.entry_time>=h.hour_of_day AND v.entry_time<DATE_ADD(h.hour_of_day,INTERVAL 1 HOUR)
WHERE h.hour_of_day BETWEEN '2017-11-20 08:00' AND '2017-11-20 12:00' -- report for period
GROUP BY h.hour_of_day
ORDER BY h.hour_of_day

SQL小提琴 - http://sqlfiddle.com/#!9/c54427/12