2012-02-18 16 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