26

我有一个有趣的问题需要做。我有一个表,其中有一INT列包含 IP 地址编号(使用INET_ATON)和一timestamp列。我希望能够计算每天存在的唯一 IP 地址列的数量。也就是说,每天有多少不同的 ip 行。因此,例如,如果一个 IP 地址在同一天出现两次,则在最终计数中计为 1,但是如果同一 IP 地址在另一天出现,则将对其进行第二次计数。

示例数据:

PK | FK  | ipNum      | timestamp
11 | 404 | 219395     | 2013-01-06 22:23:56
7  | 404 | 467719     | 2013-01-06 22:23:41
8  | 404 | 4718869    | 2013-01-06 22:23:42
10 | 404 | 16777224   | 2013-01-06 22:23:56
5  | 404 | 1292435475 | 2013-01-06 22:23:25
12 | 404 | 1526990605 | 2013-01-06 22:23:57
6  | 404 | 1594313225 | 2013-01-06 22:23:40
4  | 404 | 1610613001 | 2013-01-06 22:23:23
9  | 404 | 1628635192 | 2013-01-06 22:23:55
1  | 404 | 2130706433 | 2013-01-06 21:29:38
2  | 407 | 2130706433 | 2013-01-06 21:31:59
3  | 407 | 2130706433 | 2013-01-06 21:32:22
4

3 回答 3

79
SELECT  DATE(timestamp) Date, COUNT(DISTINCT ipNum) totalCOunt
FROM    tableName
GROUP   BY  DATE(timestamp)
于 2013-01-07T06:37:17.763 回答
4

以下是过去 7 天每天的计数方式:

select
    count(*) as count,
    date(timestamp) as date
from
    tablename
where
    timestamp >= date_sub(curdate(), interval 7 day)
group by 
    date;

+-------------+------------+
| count       | date       |
+-------------+------------+
| #forThatDay | 2020-02-21 |
| #forThatDay | 2020-02-22 |
| #forThatDay | 2020-02-22 |
| #forThatDay | 2020-02-23 |
| #forThatDay | 2020-02-24 |
| #forThatDay | 2020-02-25 |
| #forThatDay | 2020-02-26 |
+-------------+------------+
7 rows in set (0.03 sec)

首先按列分组ipNum以获得该列每天的不同计数:

select
    count(*) as count,
    date(timestamp) as date
from
    tablename
where
    timestamp >= date_sub(curdate(), interval 7 day)
group by 
    ipNum, date;

于 2020-02-27T23:22:58.293 回答
-2
$log_date     = date('Y-m-d H:i:s');
$log_date     = date('Y-m-d H:i:s', strtotime($log_date.' -1 hour'));
SELECT ipNum, COUNT(ipNum), COUNT(DISTINCT ipNum), DATE(timestamp), timestamp FROM tableName  WHERE `timestamp` > '".$log_date."' GROUP BY ipNum ORDER BY DATE(timestamp) DESC  

这会给你一个类似的结果

 ip                  TIME               COUNTIPS
11.237.115.30     2018-01-27 19:13:51       1
21.744.133.52     2018-01-27 19:14:03       1
44.628.197.51     2018-01-27 19:48:12       14
于 2018-01-27T18:36:59.130 回答