Kap*_*las 5 t-sql sql-server timestamp finance group-by
我正在使用 SQL Server 2008 R2,需要创建按时间间隔分组的新表。
该数据是来自股票市场指数的数据。我有 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
Run Code Online (Sandbox Code Playgroud)
所需查询结果(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 |....|....|...|...
Run Code Online (Sandbox Code Playgroud)
当您将 a 转换datetime
为 a时float
,您会得到天数。如果将其乘以24 * 12
,您将得到 5 分钟间隔的数量。因此,如果您分组:
cast(cast(timestamp as float) * 24 * 12 as int)
Run Code Online (Sandbox Code Playgroud)
您可以每五分钟进行一次聚合:
select min(timestamp)
, max(high) as Highest
, min(low) as Lowest
from @t
group by
cast(cast(timestamp as float) * 24 * 12 as int)
Run Code Online (Sandbox Code Playgroud)
在 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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2448 次 |
最近记录: |