SQL Min和Count

时间:2016-05-27 05:52:36

标签: sql oracle count min

我想要达到的目的是显示各类书籍的计数数量

凡数(类别)>计数(类别)中的最小数量

实施例;

如果类别

A = 1
b = 2
c = 3
D = 1
E = 1

我正在尝试显示>的类别1使用MIN。

我得到的错误是:

  

ORA-00935:群组功能嵌套太深

SELECT Count(Category),
       Category 
From Books
Having Count((Category) > MIN(Count(Category)
Group BY Category  

4 个答案:

答案 0 :(得分:4)

寻找这样的事情:

Select Count(Category),
       Category 
From Books 
Group BY Category 
Having Count(Category) > (Select Min(cnt)
                          from (Select Count(Category) AS cnt
                                From Books
                                Group By Category))

这将选择所有类别中计数大于最小数量的所有类别。

答案 1 :(得分:2)

另一种方法是rank从最低开始计数(关系被分配相同的排名)并且只选择排名大于1的行:

select * from (
    select count(*) cnt, category,
      rank() over (order by count(*)) rn
    from books
    group by category  
) t where rn > 1

答案 2 :(得分:0)

这应该这样做:

 SELECT Category, CategoryCount from
 (SELECT rownum as r, Category, Count(*) as CategoryCount
 From Books 
 Group BY Category
 Order by CategoryCount asc)
 Where r > 1;

答案 3 :(得分:0)

Giorgos的回答是正确的。它可以使用子查询因子重新排列(并且稍微提高效率):

with ctg (category, categ_count) as (
        select   category, count(*)
        from     books
        group by category
     )
select category, categ_count
from   ctg
where  categ_count > (select min(categ_count) from ctg);