2016-07-04 36 views
0

我與金融時間系列工作。我有一個用戶定義的函數,告訴我一些安全性的前一個可用交易日期。我現在正在嘗試使用用戶定義的函數來計算波動率,爲此,我需要檢查是否有前n個交易日的數據。循環中日期的T-SQL驗證?

如果沒有前一個交易日,我的日期函數返回Null。有沒有什麼可以檢查n前一個交易日?假設該函數被稱爲previous,並將參數設爲安全性iddate(然後它會檢查此日期之前是否有交易日期)。

我需要運行某種循環?

+0

這是很容易用[日曆]做(http://web.archive.org/web/20150512230546/ http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html)表或更通用的數字表。 –

回答

0

也許你調整以下

Declare @KeyDate Date ='2015-12-31' 
Declare @Days int = 15 
Declare @Ticker varchar(25) = 'AAPL' 

;with cteBase as (
    Select * 
      ,RowNr=Row_Number() over (Order By Date Desc) 
    From [Chinrus-Series].[dbo].[DS_Ticker_History] 
    Where [email protected] 
     and Date<[email protected] 
) 
Select * from cteBase where RowNr<[email protected] 

返回

enter image description here