I would like to join three tables with one condition per join (2 conditions) but I am having problems on the second join.
My tables are:
clients
| id | name | surname |
|---|---|---|
| 1 | Lois | Smitm |
| 2 | Mike | Williams |
| 3 | Jonh | Brown |
| 4 | Dustin | Jones |
| 5 | Robert | Johnson |
transactions
| id | client_id | date | amount |
|---|---|---|---|
| 1 | 1 | 2022-12-10 | 350 |
| 2 | 2 | 2022-12-11 | 350 |
| 3 | 3 | 2022-12-12 | 210 |
| 4 | 4 | 2022-12-13 | 200 |
| 5 | 5 | 2022-12-14 | 250 |
| 6 | 1 | 2022-12-15 | 450 |
| 7 | 5 | 2022-12-16 | 850 |
clients_history
| id | client_id | action | date |
|---|---|---|---|
| 1 | 1 | register | 2022-01-20 |
| 2 | 2 | register | 2022-01-21 |
| 3 | 3 | register | 2022-06-19 |
| 4 | 4 | register | 2022-03-10 |
| 5 | 5 | register | 2022-02-20 |
I would like a query that returns name and surname of those clients that have been registered between January 22 and March 22 (both included) AND the AVERAGE amount of their transactions is between 300 and 500.
I have this code but it is not working:
SELECT name, surname
FROM (
SELECT c.id, name, surname
FROM clients c
LEFT JOIN clients_history ch
ON c.id = ch.client_id
WHERE ch.action = "register"
AND ch.date >= '2022-01-01' AND ch.date<= '2022-03-31'
) AS r
LEFT JOIN transactions t
ON r.id = t.client_id
WHERE avg(t.amount) >= '300' AND avg(t.amount) <= '500'
GROUP BY t.client_id