-3

我需要获得每个月的最大 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

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

4

1 回答 1

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)for each的子查询,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

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

于 2013-04-02T18:39:13.557 回答