结果集中的sql max date

时间:2013-04-02 18:28:27

标签: sql oracle

我需要每个月获得最大的add_dtm,我有这个设置。

location, read_time,         read_amt, add_dtm
1,        2/7/2013 9:00:00,  5,        2/8/2013 6:00:00
1,        3/20/2013 8:00:00, 5,        3/20/2013 6:30:00
1,        2/20/2013 8:20:00, 5,        2/20/2013 6:35:00
1,        2/7/2013 9:00:00,  5,        2/8/2013 6:00:00

所以基本上我只需要结果中的第二行和第三行。

1 个答案:

答案 0 :(得分:1)

由于您使用的是Oracle,因此您应该能够使用row_number()等窗口函数:

select location, 
  read_time, 
  read_amt,
  add_dtm
from
(
  select location, read_time, read_amt, add_dtm,
    row_number() over(partition by location, to_char(add_dtm, 'MM-YYYY')
                      order by add_dtm desc) rn
  from yourtable
) 
where rn = 1

请参阅SQL Fiddle with Demo

或者您可以使用为每个max(add_dtm)获取location的子查询,然后将该结果加回到您的表中:

select t1.location, t1.read_time, 
  t1.read_amt, t1.add_dtm
from yourtable t1
inner join
(
  select location, max(add_dtm) MaxDate
  from yourtable
  group by location, to_char(add_dtm, 'MM-YYYY')
) t2
  on t1.location = t2.location
  and t1.add_dtm = t2.maxdate

请参阅SQL Fiddle with Demo

这两个查询的关键是您按月和年分组数据以获取最大日期。