I have some timeseries data and need to find the "last" local maximum in the series when ordered by time. Here's a sample to show what I mean:declare @t table (time_key int not null primary key, val int not null)-- easy case. here the last max is just the time_key -- when val=max(val), because there is only one maxinsert @t (time_key,val) values (1,100)insert @t (time_key,val) values (2,101)insert @t (time_key,val) values (3,106)insert @t (time_key,val) values (4,120)insert @t (time_key,val) values (5,130)insert @t (time_key,val) values (6,140) -- this is the first and last max, so desired result is time_key=6insert @t (time_key,val) values (7,130)insert @t (time_key,val) values (8,120)insert @t (time_key,val) values (9,110)insert @t (time_key,val) values (10,100)insert @t (time_key,val) values (11,90)select * from @tgodeclare @t table (time_key int not null primary key, val int not null)-- hard case - here the time for the last max is time_key=13, because that's the time where afterwards, val never increased.insert @t (time_key,val) values (1,100)insert @t (time_key,val) values (2,101)insert @t (time_key,val) values (3,130) -- first maxinsert @t (time_key,val) values (4,120)insert @t (time_key,val) values (5,130)insert @t (time_key,val) values (6,140)insert @t (time_key,val) values (7,150) -- second max insert @t (time_key,val) values (8,140)insert @t (time_key,val) values (9,130)insert @t (time_key,val) values (10,120)insert @t (time_key,val) values (11,110)insert @t (time_key,val) values (12,100)insert @t (time_key,val) values (13,110) -- this is the last max, so the desired result is time_key=13insert @t (time_key,val) values (14,100)insert @t (time_key,val) values (15,90)insert @t (time_key,val) values (16,80)select * from @tgo
Desired result is a query to give me time_key=6 for the first set of sample data, and time_key=13 for the second set.This would be easy to do in procedural code, but I am stumped on coming up with a set-based way to do it.It's not just a simple max() query because I need the time of the last local maximum, and the last local max will not be a global max in general. In the first sample it's a global max but that's only because there was only one max in that case. In the second example, there are 3 maxima, I want the time of the "last" one.thanks!
elsasoft.org