mysql - 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
任何线索为什么?有没有其他方法可以让它更简单、更干净?
谢谢。
解决方案
使用order by
和limit
;
select t.*
from t
order by year desc, month desc
limit 1;
推荐阅读
- javascript - 在 JS 处于活动状态时再次单击按钮后,如何从按钮中删除活动的类
- c# - Asp.net:命名空间“DataManager”中不存在类型或命名空间名称“Entity”(您是否缺少程序集引用?)
- node.js - 有没有办法刷新嵌入,就像用户在 discord.js 中 3 秒后再次发送命令一样?
- html - HTML/CSS 让图像用 Div 调整大小
- jenkins-pipeline - Jenkins Git 插件未获取子模块中的提交
- javascript - 使用水平滚动打开模态 javascript
- linux-kernel - 如何解析持久内存地址?
- angular - Angular:将 SQL 24 小时时间格式转换为 12 小时时间格式
- node.js - 使用 NodeJS 和 PKCS11js 库在 USB 令牌上生成/处理密钥对
- repo - 从 14 升级到 ubuntu 16 后,Repo init 因语法无效而失败