按ID表查找最大日期

按ID表查找最大日期

本文介绍了SQL-按ID表查找最大日期分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面有一个表格,我需要获取具有statut等于2的最大日期的行

Having a table below, I need to get rows with the maximum date having statut equal 2

REMUN_ID    HISTO_ID   DATE_MAJ                 STATUT
2122        7005       08/27/2014 11:10:23        2
1603        5486       08/27/2014 11:10:21        1
2122        5151       08/27/2014 11:08:36        1
1603        4710       08/27/2014 11:08:32        2

我需要按REMUN_ID获取具有最大日期和组的最大行使用此请求的结果

I need to get the row with the maximum date and group by REMUN_IDthe result using this request

select remun_id, max(date_maj)
from histo_statut_remun
group by remun_id;

结果:

REMUN_ID      DATE_MAJ
2122        08/27/2014 11:10:23
1603        08/27/2014 11:10:21

我需要调整请求以从此结果中仅获取statut = 2的行

I need to adjust the request to get only rows with statut = 2 from this result

我的目的是获取下面的结果,这是第一个查询的子查询,以仅获取具有状态2的子查询.

My purpose is to get the result below, a subquery of the first one to get only those with statut 2.

REMUN_ID    DATE_MAJ
2122        08/27/2014 11:10:23

PS:如果我使用将从中得到这些结果的子句:

PS : if i used the clause where i will get these results :

REMUN_ID     DATE_MAJ
2122        08/27/2014 11:10:23
1603        08/27/2014 11:08:32

那不是我想要的.

有什么建议吗?谢谢

推荐答案

select remun_id, date_maj
from (
  select r.*,
         max(date_maj) over (partition by REMUN_ID) as max_date
  from histo_statut_remun r
)
where date_maj = max_date
  and statut = 2;

SQLFiddle: http://sqlfiddle.com/#!4/7eb75/1

SQLFiddle: http://sqlfiddle.com/#!4/7eb75/1

这篇关于SQL-按ID表查找最大日期分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:32