2012-02-18 42 views
3

我正在使用SQL Server 2008 R2,並且需要創建按時間間隔分組的新表格。使用T-SQL將OHLC-Stockmarket數據分組爲多個時間範圍

該數據是股市指數的數據。我有1分鐘的時間間隔的數據,現在我需要5,10,15,30,45,60分鐘的時間間隔。我的主要關鍵是時間戳。

我的問題是:如何查詢1分鐘數據表以返回按特定時間間隔分組的數據,例如5分鐘間隔。

查詢必須返回該特定組中的最高,最低,最後和第一個值,最重要的還是組中時間戳的最後一個條目。

我很新的SQL語言,並試圖在網絡上找到許多代碼,但我不能得到準確返回所需的結果。

數據:

TimeStamp   | Open | High | Low | Close 
2012-02-17 15:15:0 | 102 | 110 |100 |105 
2012-02-17 15:16:0 |106 |112 |105 |107 
2012-02-17 15:17:0 | 106 |110 |98 |105 
2012-02-17 15:18:0 |105 |109 |104 |106 
2012-02-17 15:19:0 |107 |112 |107 |112 
2012-02-17 15:20:0 |115 |125 |115 |124 

所需的查詢結果(5分鐘):

Timestamp  |Open|High|Low|Close 
2012-02-15:19:0 |102 |125 |98 |124 
2012-02-15:24:0 |115.|....|...|... 
2012-02-15:29:0 |....|....|...|... 
+0

歡迎StackOverflow上:如果您發佈的代碼,XML或數據樣本,**請**突出顯示文本編輯器的線,然後點擊「代碼示例「按鈕('{}'),以便對其進行精確格式化和語法突出顯示! – 2012-02-18 11:36:14

回答

3

當轉換datetimefloat,你會得到一個天數。如果乘以24 * 12,則會得到5分鐘的間隔數。所以,如果你組:

cast(cast(timestamp as float) * 24 * 12 as int) 

你可以做骨料每五分鐘

select min(timestamp) 
,  max(high) as Highest 
,  min(low) as Lowest 
from @t 
group by 
     cast(cast(timestamp as float) * 24 * 12 as int) 

找到第一個和最後一行是SQL Server棘手。下面是使用row_number一個辦法:

select min(timestamp) 
,  max(high) as Highest 
,  min(low) as Lowest 
,  min(case when rn_asc = 1 then [open] end) as first 
,  min(case when rn_desc = 1 then [close] end) as Last 
from (
     select row_number() over (
        partition by cast(cast(timestamp as float) * 24 * 12 as int) 
        order by timestamp) as rn_asc 
     ,  row_number() over (
        partition by cast(cast(timestamp as float) * 24 * 12 as int) 
        order by timestamp desc) as rn_desc 
     ,  * 
     from @t 
     ) as SubQueryAlias 
group by 
     cast(cast(timestamp as float) * 24 * 12 as int) 

這裏有一個working example at SE Data.

+0

謝謝Andomar,這正是我所需要的東西。 – 2012-02-18 12:20:45