由于您使用的是 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。
这两个查询的关键是您按月和年对数据进行分组以获得最大日期。