我想计算某个IP的IP地址数量和日期范围,例如where date = 2017-12-01 and IP = '122.12.168.105'
。
我希望获得3列:日期,该日期的IP数量和IP本身:
| the_date |count| IP |
| 2017-12-01 | 155 | 122.12.168.105 |
目前,我提出了以下查询:
SELECT COUNT(ip), ip
FROM my_db.logs
GROUP BY ip
LIMIT 100;
但是它只返回每个IP的计数。如何按日期分组?
当我尝试在SELECT
语句中添加日期时,出现错误,指出the_date必须在GROUP_BY
子句中。但是我应该如何对IP进行分组?
答案 0 :(得分:3)
将the_date
添加到分组语句中:
SELECT the_date, COUNT(1), ip
FROM my_db.logs
GROUP BY the_date, ip
LIMIT 100;
如果列名是date
(而不是the_date
),则必须使用双引号,因为date
是a reserved word:
SELECT "date", COUNT(1), ip
FROM my_db.logs
GROUP BY "date", ip
LIMIT 100;
答案 1 :(得分:2)
我想计算某个IP的IP地址数量和日期范围,例如date = 2017-12-01和IP ='122.12.168.105'。
只需将过滤器添加为WHERE
子句即可。
SELECT COUNT(ip) as cnt, ip
FROM my_db.logs
WHERE
my_date = to_date('2017-12-01', 'yyyy-mm-dd')
AND ip = '122.12.168.105'
GROUP BY ip
LIMIT 100;
这将返回一行,其中包含给定日期给定IP在日志中出现的次数,例如:
CNT | IP
15 | 122.12.168.105
如何也按日期分组?
如果您想返回更多(非聚合)列,则需要在将它们添加到GROUP BY
时在SELECT
子句中添加它们:
SELECT COUNT(ip) as cnt, ip, my_date
FROM my_db.logs
WHERE
my_date = to_date('2017-12-01', 'yyyy-mm-dd')
AND ip = '122.12.168.105'
GROUP BY ip, my_date
LIMIT 100;
答案 2 :(得分:2)
您需要将date
添加到group by
:
SELECT the_date, ip, COUNT(ip)
FROM my_db.logs
GROUP BY the_date, ip
LIMIT 100;
通常,当使用LIMIT
时,您将拥有ORDER BY
。例如,要获取最常见的ip /日期组合:
SELECT the_date, ip, COUNT(*)
FROM my_db.logs
GROUP BY the_date, ip
ORDER BY COUNT(*) DESC
LIMIT 100;