SQL - Finding the maximum date group by id table

落爺英雄遲暮 提交于 2019-11-28 05:59:42

问题


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 

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

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

Result :

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

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

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 : 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         

and that's not what i want to get.

Any suggestions? Thank you


回答1:


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



来源:https://stackoverflow.com/questions/25529320/sql-finding-the-maximum-date-group-by-id-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!