按日期和时间对数据进行分组和统计,间隔为一小时

时间:2017-08-07 15:06:19

标签: php mysql

我正在保存(PHP)用户对mySQL dB的访问,如下所示

|    IP Number    |     date    |   time  |
-------------------------------------------
|  193.12.143.145 |  2017-03-05 | 15:02   |
|  121.144.98.201 |  2017-03-05 | 15:38   |
|  188.34.12.167  |  2017-05-18 | 09:13   |
|  191.13.122.201 |  2017-05-18 | 09:51   |
|  167.98.101.157 |  2017-06-22 | 11:44   |
-------------------------------------------

我希望日期时间 groupcount IP,间隔一小时,以便预期的产出是:

|     date    |   time  | count |
---------------------------------
|  2017-03-05  | 15:00  |   2   |
|  2017-05-18  | 09:00  |   2   |
|  2017-06-22  | 11:00  |   1   |
---------------------------------

我尝试了在Stackoverflow上找到的答案,但没有产生所需的结果。请注意,第二个表将小时数打印为15:00,9:00,11:00。

1 个答案:

答案 0 :(得分:3)

创建表/插入数据

CREATE TABLE Table1
    (`IP Number` VARCHAR(14), `date` DATE, `time` VARCHAR(5))
;

INSERT INTO Table1
    (`IP Number`, `date`, `time`)
VALUES
    ('193.12.143.145', '2017-03-05', '15:02'),
    ('121.144.98.201', '2017-03-05', '15:38'),
    ('188.34.12.167', '2017-05-18', '09:13'),
    ('191.13.122.201', '2017-05-18', '09:51'),
    ('167.98.101.157', '2017-06-22', '11:44')
;

<强>查询

SELECT 
   DATE
 , CONCAT(TIME_FORMAT(TIME, "%H"), ":00") AS TIME
 , COUNT(*) AS COUNT
FROM table1 
GROUP BY
   DATE
 , CONCAT(TIME_FORMAT(TIME, "%H"), ":00") 

<强>结果

date        time     count  
----------  ------  --------
2017-03-05  15:00          2
2017-05-18  09:00          2
2017-06-22  11:00          1