2015-12-02 34 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 
;