﻿CREATE PROCEDURE [dbo].[KST_GetUpdatedLiveRates]
	@SearchItemsList [dbo].[LiveRateSearchItemsList] readonly
AS
	SELECT 
		a.[CRTD_CreationDate] as 'Timestamp'
		,a.[CRTD_BidOpeningValue] as 'BidOpen'
		,a.[CRTD_BidClosingValue] as 'BidClose'
		,MIN(a.[CRTD_BidLowValue]) as 'BidLow'
		,MAX(a.[CRTD_BidHighValue]) as 'BidHigh'
		,a.[CRTD_PairSymbol] as 'PairSymbol'
		,CAST(a.[ExchangeId] AS int) as 'ExchangeId'

	FROM [dbo].[CRT_Data_LiveChart] a with (nolock) 
	WHERE EXISTS(SELECT 1 FROM  @SearchItemsList l WHERE l.ExchangeId = a.ExchangeId AND l.PairSymbol = a.CRTD_PairSymbol AND l.LaterThanDate < a.[CRTD_CreationDate])
	--LEFT OUTER JOIN [dbo].[CRT_Data_LiveChart] b ON a.[CRTD_PairSymbol] = b.[CRTD_PairSymbol] AND a.ExchangeId = b.ExchangeId AND a.[CRTD_Period] < b.[CRTD_Period]
	--WHERE b.[CRTD_PairSymbol] IS NULL
	GROUP BY a.[CRTD_CreationDate] ,a.[CRTD_PairSymbol], a.[ExchangeId], a.[CRTD_BidOpeningValue],a.[CRTD_BidClosingValue] 
		--a.[CRTD_BidLowValue] ,a.[CRTD_BidHighValue]		
		HAVING(a.[CRTD_CreationDate] = MAX(a.[CRTD_CreationDate]))
	ORDER BY a.[CRTD_CreationDate] DESC;

	
