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

/*Вычисление разности курсов валют*/

declare @currencyKey int;
set @currencyKey = 3;
select timeKey, AverageRate,   
  (select AverageRate 
   from FactCurrencyRate as f2 
   where f2.timeKey = f1.timeKey + 1 and currencyKey=f1.currencyKey)
  as nextAvarageRate,
  (select AverageRate 
   from FactCurrencyRate as f2 
   where f2.timeKey = f1.timeKey - 1 and currencyKey=f1.currencyKey) 
  as lastAvarageRate
from FactCurrencyRate as f1
where currencyKey = @currencyKey 
		and 
     Averagerate > (select AverageRate 
					from FactCurrencyRate as f2 
					where f2.timeKey = f1.timeKey + 1 and currencyKey=f1.currencyKey)
		and
     Averagerate > (select AverageRate 
					from FactCurrencyRate as f2 
					where f2.timeKey = f1.timeKey - 1 and currencyKey=f1.currencyKey)