Mysql SQL检索与最高日期匹配的id,该id由另一个字段分组
我有以下数据: 我想检索与最高日期(由Mysql SQL检索与最高日期匹配的id,该id由另一个字段分组,mysql,sql,group-by,Mysql,Sql,Group By,我有以下数据: 我想检索与最高日期(由max(folga)表示)匹配的id,按functionario\u id分组 这是我想要的输出表,但它缺少id: 我怎样才能做到这一点 感谢您的关注。一种方法是使用不存在: select t.funcionario_id, t.folga, t.id from tablename t where not exists ( select 1 from tablename where funcionario_id = t.funcionario
max(folga)
表示)匹配的id
,按functionario\u id
分组
这是我想要的输出表,但它缺少id:
我怎样才能做到这一点
感谢您的关注。一种方法是使用
不存在:
select
t.funcionario_id, t.folga, t.id
from tablename t
where not exists (
select 1 from tablename
where funcionario_id = t.funcionario_id and folga > t.folga
)
或者,您可以先按Functionario_id进行分组
以获取最大日期(我猜这是返回您发布的结果的查询),然后加入表:
select t.*
from tablename t inner join (
select funcionario_id, max(folga) folga
from tablename
group by funcionario_id
) g on g.funcionario_id = t.funcionario_id and g.folga = t.folga
到目前为止你试过什么?另外,您得到的是什么而不是预期的输出?你所说的是什么意思,但它缺少id
?如果你在谷歌上看一下,这是一个简单的问题<代码>按Functionario_id从TableName组中选择Functionario_id,MAX(folga)谢谢你抽出时间,但你好像不明白。我发送的第二个图像返回的正是您的查询所建议的内容,但正如我所说,我希望id字段与输出中的最高日期相匹配。我很高兴有人在这方面为您提供了帮助,但我不明白您为什么需要提供格式更好的问题。请阅读如何提供一个你也可能受益于谢谢你的福帕!我很难想出怎么做。我花了一段时间才明白你的第一个解决方案。我将测试这两种方法,稍后标记答案。