PLSQL - COUNT“N”MAX值

时间:2011-06-23 09:57:13

标签: plsql

下表:(列:ID-CAUSE-WORK)

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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)