【问题标题】:SQL - Finding the maximum date group by id tableSQL - 通过 id 表查找最大日期组
【发布时间】:2014-08-27 14:06:27
【问题描述】:

下面有一个表格,我需要获取最大日期为 statut 等于 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 获取最大日期和分组的行 使用此请求的结果

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 的行

我的目的是得到下面的结果,第一个子查询的子查询只得到那些状态为 2 的结果。

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

PS:如果我使用了我会得到这些结果的子句:

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

这不是我想要的。

有什么建议吗? 谢谢

【问题讨论】:

  • SQL-Server、Oracle、Postgres、MySQL、DB2、SQLite,什么?你在用什么?
  • 在 GROUP BY 之后添加 HAVING SUM(CASE WHEN statut=2 THEN 1 END)>0

标签: sql oracle greatest-n-per-group


【解决方案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

【讨论】:

  • 我认为在这里使用MAX(date)是不安全的
  • @Bulat:如果同一个remun_id 有多个日期等于最高日期,这一切都取决于 hb.sara 是否希望查看多行。
猜你喜欢
  • 2015-03-12
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 2019-03-21
  • 2015-05-30
  • 1970-01-01
  • 2017-09-04
相关资源
最近更新 更多