Write a query to display the patron ID, last name, number of times that patron has ever checked out a book, and the number of different books the patron has ever checked out. For example, if a given patron has checked out the same book twice, that would count as two checkouts but only one book. Limit the results to only patrons who have made at least three checkouts. Sort the results in descending order by number of books, then in descending order by number of checkouts, and then in ascending order by patron ID.
时间: 2024-03-11 15:43:26 浏览: 192
Sure, here's the SQL query that will display the required information:
```
SELECT p.patron_id, p.last_name, COUNT(*) AS num_checkouts, COUNT(DISTINCT b.book_id) AS num_books
FROM patrons p
JOIN checkouts c ON p.patron_id = c.patron_id
JOIN books b ON c.book_id = b.book_id
GROUP BY p.patron_id
HAVING num_checkouts >= 3
ORDER BY num_books DESC, num_checkouts DESC, p.patron_id ASC;
```
This query joins the `patrons`, `checkouts`, and `books` tables together, and groups the results by patron ID. The `COUNT()` function is used to count the number of checkouts and the number of distinct books that each patron has checked out. The `HAVING` clause filters out patrons who have made less than three checkouts, and the `ORDER BY` clause sorts the results as required.
阅读全文