PLSQL-COUNT个“ N”个最大值

问题描述

| 下表如下:(各列: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
    

解决方法

        这应该工作:
select cause,work,cnt as \"COUNT\"
from (
  select cause,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;
    ,        
select cause,Count from 
(
   select cause,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)