我正在保存(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 |
-------------------------------------------
我希望日期和时间 group
和count
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。
答案 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