I have three tables:
students
|id_number| name
| 1001 | Brian |
| 1002 | John |
terms
| id | year | term | label |
| 10 | 2022 | 3 | Summer |
| 11 | 2023 | 1 | 1st Sem |
| 12 | 2023 | 2 | 2nd Sem |
| 13 | 2023 | 3 | Summer |
history
|id_number | terms_id | section |
| 1002 | 11 | Oak |
| 1002 | 13 | Fig |
| 1002 | 12 | Daisy |
| 1001 | 10 | Daisy |
Now I want to get the most recent section of each student. All these three tables are expected to be populated with more rows in the coming years.
Desired Result:
| id_number | section |
| 1002 | Fig |
| 1001 | Daisy |
I tried this query but I think I lack something or am having the wrong logic. Note that year*3+term
will help me achieve the terms in the right order, i.e, 1st, 2nd and summer order.
SELECT s.id_number, h.section
FROM students s
LEFT JOIN history h ON s.idno = h.idno
LEFT JOIN terms t ON t.id = h.terms_id
LEFT JOIN (SELECT id, year*3 + term AS ext_term FROM terms) ext ON ext.id = t.id
WHERE
t.id = (
SELECT MAX(ext_term)
FROM ext
WHERE ext.id = t.id
)