gpt4 book ai didi

sql-server - 使用 T-SQL 将 OHLC 股票市场数据分组为多个时间范围

转载 作者:行者123 更新时间:2023-12-03 03:26:58 25 4
gpt4 key购买 nike

我正在使用 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

期望的查询结果(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 |....|....|...|...

最佳答案

当您将日期时间转换为浮点时,您会得到天数。如果将其乘以 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.

关于sql-server - 使用 T-SQL 将 OHLC 股票市场数据分组为多个时间范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9340602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com