/*Локальные максимумы курса валюты (с использованием цикла)*/
declare @cr int; set @cr=102;     --код валюты
declare @tid int;
declare @tidc int;
set @tid = (select min(TimeKey) from FactCurrencyRate where CurrencyKey=@cr) + 1
--select 't' = @tid
declare @tt table(tid int, rate float, flag int)
while exists (select * from FactCurrencyRate where CurrencyKey=@cr and TimeKey = @tid)
begin
   declare @a0 float, @a1 float, @a2 float;
   set @a0 = (select AverageRate from FactCurrencyRate 
                  where CurrencyKey=@cr and TimeKey = @tid - 1)
   set @a1 = (select AverageRate from FactCurrencyRate 
                  where CurrencyKey=@cr and TimeKey = @tid)
   set @a2 = (select AverageRate from FactCurrencyRate 
                  where CurrencyKey=@cr and TimeKey = @tid + 1)
   if @a0 < @a1 and @a1 > @a2
   begin
      insert into @tt(tid, rate, flag) values(@tid - 1, @a0, 0)
      insert into @tt(tid, rate, flag) values(@tid , @a1, 1)
      insert into @tt(tid, rate, flag) values(@tid + 1, @a2, 2)
   end  
 
  set @tid = @tid + 1;
end

select * from @tt