/*Локальные максимумы курса валюты (с использованием дополнительных таблиц)*/


declare @cr int; set @cr=102;
declare @tid_min int;
declare @tid_max int;
set @tid_min = (select min(TimeKey) from FactCurrencyRate where CurrencyKey=@cr)
set @tid_max = (select max(TimeKey) from FactCurrencyRate where CurrencyKey=@cr)
declare @tt0 table(tid int, rate float)
declare @tt1 table(tid int, rate float)
declare @tt2 table(tid int, rate float)

insert into @tt0 select TimeKey + 1, AverageRate from FactCurrencyRate 
                   where CurrencyKey=@cr and 
                         TimeKey between @tid_min and @tid_max - 2

insert into @tt1 select TimeKey, AverageRate from FactCurrencyRate 
                   where CurrencyKey=@cr and 
                         TimeKey between @tid_min + 1 and @tid_max - 1

insert into @tt2 select TimeKey - 1, AverageRate from FactCurrencyRate 
                   where CurrencyKey=@cr and 
                         TimeKey between @tid_min + 2 and @tid_max
select t1.tid, t0.rate, t1.rate, t2.rate 
from   @tt0 t0 inner join @tt1 t1 on t0.tid = t1.tid
               inner join @tt2 t2 on t2.tid = t1.tid
where  t0.rate < t1.rate and t1.rate > t2.rate