Senior
Write an SQL query to select the names of the three most read authors currently (those with the most books on hand).
sobes.tech AI
Answer from AI
Suppose we have the following tables:
authors(id, name)books(id, author_id)loans(id, book_id, loan_date, return_date)
To select the names of the three authors who currently have the most books on loan (i.e., books that are borrowed and not yet returned), you can write the following query:
SELECT a.name, COUNT(*) AS books_on_loan
FROM authors a
JOIN books b ON a.id = b.author_id
JOIN loans l ON b.id = l.book_id
WHERE l.return_date IS NULL
GROUP BY a.id, a.name
ORDER BY books_on_loan DESC
LIMIT 3;
This query counts the number of books for each author that are currently not returned (return_date IS NULL), sorts the results in descending order, and retrieves the top 3.