2015-12-02 35 views
1

表是这样排序的列,说这表示在日志文件中各类事件的选择由计数,但不计

<type> <date> 

我想选择前5个最常见的类型

select type,count(type) as c from log order by c desc limit 5 

这工作正常,但我只想要类型列,所以我可以使用这是一个where in子查询。我怎么做?我不能工作,如何剿计数科拉姆

回答

0

很简单:

SELECT type FROM log GROUP BY type ORDER BY COUNT(type) DESC LIMIT 5 
+0

erm * ....但我只想要类型列... * –

+0

@TomRedfern,你说得对,修好了。 –

+0

我曾尝试过,我的分贝(sqlite)说“滥用聚合计数()” – pm100

0

就使这个子查询过:

SELECT TYPE 
FROM LOG 
WHERE TYPE IN 
    (select type,count(type) as c 
    from log 
    order by c desc limit 5) 
+0

你的意思是从选择类型(select type,count(type)....)。 – pm100

+0

是的,我会编辑显示您的查询清晰 –

0

不使用SQLite的,但我会写这样的事情在SQL服务器中;也许有一些想法可以偷走?

select top (5) type from log group by type order by count(type) desc 
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 
;