Second-Most Borrowed Book by Country | Chill Interview
Second-Most Borrowed Book by Country
Asked by:
LimeOA
An international library network records every book loan and the branch where it occurred. The catalog team wants to identify books at the second-highest distinct borrowing level within each country.
Table: books
+--------------+--------------+
| Column Name | Type |
+--------------+--------------+
| book_id | integer |
| title | varchar(255) |
| genre | varchar(255) |
| published_on | date |
+--------------+--------------+
+--------------+--------------+
| Column Name | Type |
+--------------+--------------+
| book_id | integer |
| title | varchar(255) |
| genre | varchar(255) |
| published_on | date |
+--------------+--------------+
book_id is the primary key. Each row contains catalog information for one book.
loan_id is the primary key. Each row represents one completed book loan.
Table: library_branches
+-------------+--------------+
| Column Name | Type |
+-------------+--------------+
| branch_id | integer |
| branch_name | varchar(255) |
| country | varchar(255) |
+-------------+--------------+
+-------------+--------------+
| Column Name | Type |
+-------------+--------------+
| branch_id | integer |
| branch_name | varchar(255) |
| country | varchar(255) |
+-------------+--------------+
branch_id is the primary key. Each row identifies a library branch and its country.
For each country, count the loans for every book across all branches in that country. Rank books by their loan count using distinct ranks: books with equal counts share the same rank, and the next different count receives the next rank.
Return every book whose loan count has rank 2 within its country. This is the second-highest distinct loan count, so all ties at that level must be included.
Books with no loans are excluded. If a country has only one distinct positive loan count—for example, all borrowed books are tied for the highest count—return no row for that country.
Return country, book_id, and loan_count. Order the results by country ascending, then book_id ascending.