Marcin :
I have following table:
id year month
1 2019 9
2 2019 10
3 2019 11
4 2019 12
5 2020 1
6 2020 2
7 2020 3
8 2020 4
I need to select max value of column month but only from where year has got max value. In that case i need to select row
id max_year max_month
8 2020 4
I tried to make it with this
SELECT m.id, m.max_year, MAX(m.month) AS max_month FROM (SELECT id, month, MAX(year) AS max_year FROM tbl_months GROUP BY id) AS m GROUP BY m.id
Unnfortunately I get
id max_year max_month
5 2020 1
6 2020 2
7 2020 3
8 2020 4
Any clues why? Is there another way to make it simpler and cleaner?
Thanks.
Gordon Linoff :
Use order by
and limit
;
select t.*
from t
order by year desc, month desc
limit 1;