首页 > 解决方案 > SQL查找另一列具有最大值但可重复值的列的最大值

问题描述

我有下表:

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

我需要选择列月份的最大值,但只能从年份获得最大值的地方选择。在那种情况下,我需要选择行

id  max_year    max_month
8   2020        4

我试着用这个

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

不幸的是我得到

id  max_year    max_month
5   2020    1
6   2020    2
7   2020    3
8   2020    4

任何线索为什么?有没有其他方法可以让它更简单、更干净?

谢谢。

标签: mysqlsqlmax

解决方案


使用order bylimit;

select t.*
from t
order by year desc, month desc
limit 1;

推荐阅读