表就像这样,假设它代表日志文件中的各种类型的事件
<type> <date>
我想选择前5种最常见的类型
select type,count(type) as c from log order by c desc limit 5
这工作正常,但我只想要类型列,所以我可以使用它是一个where in
子查询。我怎么做?我无法弄清楚如何压制伯爵colum
答案 0 :(得分:1)
您没有指定RDBMS,这在很大程度上取决于您使用的是哪一个。这里有一些选择。
-- works in postgres and mysql
select type from log group by type order by count(*) desc limit 5;
-- this variant works in mssql but probably no where else (maybe sybase)
select top(5) type from log group by type order by count(*) desc;
-- works in posgres and mssqlserver but not mysql or oracle
select
type
from (select
type,
row_number() over (order by count(*) desc) as r
from
log
group by
type
) as t
where
r <= 5
;
-- portable to all standards compliant RDMS
select
type
from (select
type,
row_number() over (order by c) as r
from
(select
type,
count(*) as c
from
log
group by
type
) as t
) as t
where
r <= 5
;
-- works if you don't have windowing functions, but returns more than 5 rows
select
type
from
(select
type,
count(*) as c
from
log
group by
type
) as t
order by
c desc
;
答案 1 :(得分:0)
非常简单:
SELECT type FROM log GROUP BY type ORDER BY COUNT(type) DESC LIMIT 5
答案 2 :(得分:0)
也可以将其作为子查询:
SELECT TYPE
FROM LOG
WHERE TYPE IN
(select type,count(type) as c
from log
order by c desc limit 5)
答案 3 :(得分:0)
没用过sqlite,但是我会在SQL server中写这样的东西;也许有一些想法你可以偷?
select top (5) type from log group by type order by count(type) desc