SQL finding max value of column where another column has got maximum but repetable value

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;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=8439&siteId=1