我发现的这个问题让我发疯,(编辑:)因为我试图在没有按方法排序的情况下实现这一目标。我有一张桌子:
BookAuthors(书,作者)
book author
------ ---------
1 Joy McBean
2 Marti McFly
2 Joahnn Strauss
2 Steven Spoilberg
1 Quentin Toronto
3 Dr E. Brown
书籍和作者都是关键。
现在我想选择不同“作者”数量最多的“书”值,以及作者的数量。在我们的例子中,查询应该检索有 3 个作者的“书”2。
book authors
-------- ------------
2 3
我已经能够将它们分组并使用此查询获取每本书的作者数量:
select B.book, count(B.author) as authors
from BookAuthors B
group by B.book
这将导致:
book authors
-------- -------------
1 2
2 3
3 1
现在我只想获得作者数量最多的书。这是我尝试过的查询之一:
select Na.libro, Na.authors from (
select B.book, count(B.author) as authors
from BookAuthors B
group by B.book
) as Na
where Na.authors in (select max(authors) from Na)
和
select Na.libro, Na.authors from (
select B.book, count(B.author) as authors
from BookAuthors B
group by B.book
) as Na
having max( Na.authors)
我有点挣扎……
感谢您的帮助。
编辑:由于@Sebas 很乐意回答正确并扩展我的问题,因此我想到了使用 CREATE VIEW 方法的解决方案:
create view auth as
select A.book, count(A.author)
from BooksAuthors A
group by A.book
;
进而
select B.book, B.nAuthors
from auth B
where B.nAuthors = (select max(nAuthors)
from auth)