Borrows per Patron in 2023
Problem
Table: `Patrons`
```text
+----------------+---------+
| Column | Type |
+----------------+---------+
| patron_id | int |
| signup_day | date |
| favorite_genre | varchar |
+----------------+---------+
patron_id is the primary key.
```
Table: `Loans`
```text
+------------+---------+
| Column | Type |
+------------+---------+
| loan_id | int |
| loan_day | date |
| book_id | int |
| patron_id | int |
| clerk_id | int |
+------------+---------+
loan_id is the primary key. patron_id is the patron who borrowed the book.
```
For every patron, return their `patron_id`, their `signup_day`, and the number
of books they borrowed during the year **2023**. Patrons who borrowed nothing
in 2023 should still appear with a count of 0. Name the count column
`loans_in_2023`.
**Example**
```text
Patrons:
+-----------+------------+----------------+
| patron_id | signup_day | favorite_genre |
+-----------+------------+----------------+
| 1 | 2022-01-10 | fantasy |
| 2 | 2023-03-05 | history |
+-----------+------------+----------------+
Loans:
+---------+------------+---------+-----------+----------+
| loan_id | loan_day | book_id | patron_id | clerk_id |
+---------+------------+---------+-----------+----------+
| 100 | 2023-02-01 | 9 | 1 | 50 |
| 101 | 2022-12-30 | 8 | 1 | 50 |
+---------+------------+---------+-----------+----------+
Output:
+-----------+------------+---------------+
| patron_id | signup_day | loans_in_2023 |
+-----------+------------+---------------+
| 1 | 2022-01-10 | 1 |
| 2 | 2023-03-05 | 0 |
+-----------+------------+---------------+
```
Patron 1 has one loan dated in 2023 (the 2022 loan does not count). Patron 2
has no loans, so 0.
Tables
Example rows — the live problem includes the full dataset.
| patron_id | signup_day | favorite_genre |
|---|---|---|
| 1 | 2022-01-10 | fantasy |
| 2 | 2023-03-05 | history |
| loan_id | loan_day | book_id | patron_id | clerk_id |
|---|---|---|---|---|
| 100 | 2023-02-01 | 9 | 1 | 50 |
| 101 | 2022-12-30 | 8 | 1 | 50 |
Expected output
Your answer should return 2 rows with the columns patron_id, signup_day, loans_in_2023.
Starter code (SQL)
SELECT *
FROM Patrons;Solve this SQL question free
Write SQL and run it instantly in your browser — even on your phone. No signup needed to try.
Solution & explanation
Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.
Sign up free to unlock