Group OHLC-Stockmarket Data into multiple timeframes with T-SQL

痞子三分冷 提交于 2019-12-04 14:28:57

When you convert a datetime to a float, you get a number of days. If you multiply that by 24 * 12, you get a number of 5 minute intervals. So if you group on:

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

you can do aggregates per five minutes:

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

Finding the first and the last row is tricky in SQL Server. Here's one way using 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)

Here's a working example at SE Data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!