使用特定条件计数后查找最大值

时间:2017-10-25 16:11:06

标签: sql oracle

我正在尝试找到分配了最大空值的部门。 这是表Class:

Dept    Assigned
CSCE    
CSCE    
ELEG     4
ELEG     
MATH     
ELEG     

因此,由于CSCE和ELEG分配的空值最大,我想输出。

Dept   Max(Count)
CSCE   2
ELEG   2 

这就是我所拥有的:

Select Dept, Max(Countt)
from (Select Dept, Count(Dept) as Countt
      from Class
      where assigned is null group by Dept
     );

然而,它正在输出包括数学在内的所有部门的计数。我该如何解决这个问题?

我正在使用Oracle。

2 个答案:

答案 0 :(得分:0)

您可以使用窗口函数:

select d.Dept, cnt
from (select c.Dept, Count(*) as cnt,
             rank() over (order by count(*) desc) as seqnum
      from Class c 
      where c.assigned is null
      group by c.Dept
     ) d
where seqnum = 1;

答案 1 :(得分:0)

另一种方式:

select count(*), dept from table
where assigned is null
group by dept
having count(*) = (select max(c) from (select count(*) as c from table
                   where assigned is null
                   group by dept) as t)