I am building a library database. I want to write a query that returns the top 5 books for each category, which means that it has to return the 5 books that are borrowed the most times for each one of the categories and the number of times they are borrowed.
The query involves the following tables:
Book (ISBN, title,pubYear,numpages, pubName)
borrows (memberID, ISBN, copyNr, date_of_borrowing, date_of_return)
belongs_to (ISBN, categoryName)
My approach is the following:
SELECT *
FROM(SELECT book.title, count(bo.ISBN) as Number_of_times_book_is_taken ,be.categoryName
FROM belong_to as be INNER JOIN borrows as bo ON be.ISBN = bo.ISBN INNER JOIN book ON bo.ISBN = book.ISBN
GROUP BY bo.ISBN
ORDER BY count(bo.ISBN) DESC) AS Popular
ORDER BY categoryName, Number_of_times_book_is_taken DESC
I consider this works fine if I wanted to return the titles of the books, the number of times the books are taken and the category in which they belong.
However, I want to restrict the resutls so that I get only 5 books for each of the categories. If I use LIMIT 5
I will limit the whole result, which is not what I want. I am trying to limit each one of the categoryNames to appear max 5 times.