SQL使用Count()查找频率不是MAX的ID

时间:2018-02-02 22:29:27

标签: mysql sql

我有一个名为book_author的表,其架构(book_id:int,author:string)。

我正在努力获得作者数量第二高的书籍。

那就是说,如果表格是这样的:

book_id   |   author
_____________________
1         |   John
2         |   Anna
3         |   Dan
1         |   Robert
2         |   Kim
1         |   Oscar
3         |   Bill

回归将是这样的。 Book_id = 1不在表中,因为它具有最大值

book_id    | NUM_AUTHORS
2          |  2
3          |  2

我的初步尝试如下,但这只是返回带有最大作者数量的书ID,而不是第二个到最大的...我可以修改这个吗?

SELECT book_id, COUNT(*) AS NUM_AUTHORS FROM book_author GROUP BY book_id 
HAVING COUNT(*) = 
(SELECT MAX(c) FROM
(SELECT COUNT(book_id) AS c
FROM book_author
GROUP BY book_id));

1 个答案:

答案 0 :(得分:3)

您可以按降序排列计数并获取第二行(带偏移和限制)来执行此操作

select book_id,count(*)
from book_author
group by book_id
having count(*) = (select distinct cnt
                   from (select count(*) as cnt
                         from book_author 
                         group by book_id 
                        ) t
                   order by cnt desc 
                   limit 1 offset 1
                  )