2011-06-23 74 views
0

有如下表所示:(列:ID-原因-WORK)PLSQL - COUNT 「N」 最大值

ID | CAUSE | WORK 
A | C1 | W1 
B | C1 | W1 
C | C1 | W1 
D | C1 | W1 
E | C1 | W2 
F | C1 | W2 
G | C1 | W2 
H | C1 | W3 
I | C1 | W3 
FF | C2 | W4 
FG | C2 | W4 
FG | C2 | W1 
FG | C2 | W1 
FG | C2 | W6 

我想每個事業工作的計數的兩個最高值。也就是說,用一個簡單的計數(工作組)的原因,其結果必然是:

cause | work| count(work) 
c1 | w1 | 4 
c1 | w2 | 3 
c1 | w3 | 2 
c2 | w4 | 2 
c2 | w1 | 2 
c2 | w6 | 1 

我想只拿2最大計數每事業的作品:

c1 | w1 | 4 
c1 | w2 | 3 
c2 | w4 | 2 
c2 | w1 | 2 

回答

1

這應該工作:

select cause, 
     work, 
     cnt as "COUNT" 
from (
    select cause, 
     work, 
     count(work) as cnt, 
     row_number() over (partition by cause order by count(work) desc, work desc) as rown 
    from your_table group by cause, work 
) where rown <= 2; 
+0

它的工作原理非常完美。謝謝。 – veg123

+0

如果您對結果滿意,請將問題標記爲已回答,謝謝。 http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –

0
select cause,work,Count from 
(
    select cause,work,Count(Work) as Count 
    from table_name 
    group by cause,work 
) 
where Count = (select Max(Count(Work)) as Count 
       from table_name 
       group by cause,work) 
+0

嗨,查詢返回只有一個唯一值的最大數量。我的需求是在我的例子中,每個原因= 4個值的最大工作數量爲2 – veg123