从多对多关系获得最大数量(未正确结束)

时间:2018-01-04 06:43:59

标签: oracle

我有2个表与多对多关系

book
-----
|ID |
-----
 1  
 2 
 3  


book_category
-----------------------
|book_id|category_id |
-----------------------
 1       |1
 2       |1
 3       |2


category
----------
|id|name |
----------
 1 |1
 2 |1
 3 |2

我需要显示最常见类别的名称 我正在尝试这个查询

     select name,num from category inner join 
     (select category_id, count(book_id) as num from book_category group by 
      category_id) on id = category_id
        where num >= all (select count(book_id) from book_category group by 
        category_id) on id = category_id) 

并且sql命令未正确结束。 尝试了许多不同的东西仍然没有工作,任何帮助表示赞赏。 谢谢^ _ ^

1 个答案:

答案 0 :(得分:0)

从内部查询开始到外部查询,我们对所有count(book_id)采用category_id,按降序排列它们,然后根据rank = 1条件过滤条目/条目。即使有多个category_id具有相同的最高count(book_id),您也会在结果中看到所有这些SELECT B.CATEGORY_ID, B.NUM FROM ( SELECT A.CATEGORY_ID, A.NUM, DENSE_RANK() OVER (ORDER BY A.NUM DESC) AS MOST_COMMON_RANK FROM (SELECT CATEGORY_ID, COUNT(BOOK_ID) AS NUM FROM BOOK_CATEGORY GROUP BY CATEGORY_ID ORDER BY COUNT(BOOK_ID) DESC) A ) B WHERE B.MOST_COMMON_RANK = 1;

{{1}}