I have a table called balances. I want to get the most recent balance for each user, forever every financial year and its corresponding date it was updated.
| name | balance | financial_year | date_updated |
|---|---|---|---|
| Bob | 20 | 2021 | 2021-04-03 |
| Bob | 58 | 2019 | 2019-11-13 |
| Bob | 43 | 2019 | 2022-01-24 |
| Bob | -4 | 2019 | 2019-12-04 |
| James | 92 | 2021 | 2021-09-11 |
| James | 86 | 2021 | 2021-08-18 |
| James | 33 | 2019 | 2019-03-24 |
| James | 46 | 2019 | 2019-02-12 |
| James | 59 | 2019 | 2019-08-12 |
So my desired output would be:
| name | balance | financial_year | date_updated |
|---|---|---|---|
| Bob | 20 | 2021 | 2021-04-03 |
| Bob | 43 | 2019 | 2022-01-24 |
| James | 92 | 2021 | 2021-09-11 |
| James | 59 | 2019 | 2019-08-12 |
I've attempted this but found that using max() sometimes does not work since I use it across multiple columns
SELECT name, max(balance), financial_year, max(date_updated)
FROM balances
group by name, financial_year