【发布时间】:2016-09-13 10:36:55
【问题描述】:
我有一个非常简单的表 (LOG),其中包含属性 MAC_ADDR、IP_SRC、IP_DST、URL、PROTOCOL。当 PROTOCOL='DNS' 时,我希望包含 IP_SRC、URL、#OfOccurrences 的前 n 行通过减少表中每个 IP_SRC 的 #OfOccurrences 来排序。
为了更清楚,我希望能够为我的表中的每个 IP_SRC 列出前 n 个访问次数最多的页面。
我可以像这样获取每个 IP_SRC 的访问次数最多的 URL:
select ip_src,url,cnt
from (
select ip_src,url,count(*) as cnt,protocol
from log as b group by ip_src,url order by ip_src,cnt desc
) as c
where cnt>=(select MAX(cpt)
from (select count(*) as cpt from log as b
where c.ip_src==b.ip_src group by ip_src,url)
)
and protocol='DNS';
但是,这个方案显然没有优化。
这是一个更实用的代码(每个 IP_SRC 的访问量最大的 URL):
select ip_src,url,cnt
from (select ip_src,url,count(*) as cnt
from log where protocol='DNS'
group by ip_src,url
order by ip_src,cnt asc)
group by ip_src;
第二个选项更快!但是,我想要每个 IP_SRC 的 n 个访问次数最多的页面,但我不知道该怎么做。
感谢您的帮助。
【问题讨论】:
-
标记您正在使用的 dbms。 (那里有一些无效的 SQL...)
-
@jarlh 谢谢,确实是 sqlite。
标签: sql sqlite join limit-per-group