I work with some data that is currently stored at 1 minute intervals, which looks like this:
CREATE TABLE
Values track exchange rates, therefore, for each minute interval (bar) per minute, the Open and Close prices start per minute. The High and Low values represent the highest and lowest speeds for each individual minute.
Desired Result
I want to reformat this data at 5 minute intervals to get the following result:
MinuteBar Open Close Low High 2015-01-01 17:00:00.000 1.557870 1.558030 1.557870 1.558100 2015-01-01 17:05:00.000 1.558580 1.557970 1.557870 1.558710
This takes the Open value from the first minute of the value 5, Close from the last minute of 5. The High and Low values represent the highest High and lowest Low rates for the 5-minute period.
Current solution
I have a solution that does this (below), but it feels inelegant as it relies on id and self join values. In addition, I intend to run it on much larger datasets, so I tried to do it more efficiently, if possible:
-- Create a column to allow grouping in 5 minute Intervals SELECT Id, MinuteBar, [Open], High, Low, [Close], DATEDIFF(MINUTE, '2015-01-01T00:00:00', MinuteBar)/5 AS Interval INTO
Attempt Rework
Instead of the above requests, I considered using FIRST_VALUE and LAST_VALUE , because it seems to me that I am behind it, but I can not get it to work with the group that I am doing. There may be a better solution than what I'm trying to do, so I am open to suggestions. I am currently trying to do this:
SELECT MIN(MinuteBar) MinuteBar5 , FIRST_VALUE([Open]) OVER (ORDER BY MinuteBar) AS Opening, MAX(High) AS High , MIN(Low) AS Low , LAST_VALUE([Close]) OVER (ORDER BY MinuteBar) AS Closing , DATEDIFF(MINUTE, '2015-01-01 00:00:00', MinuteBar) / 5 AS Interval FROM
This gives me the following error related to FIRST_VALUE and LAST_VALUE as the query runs if I delete these lines:
The column # MinuteData.MinuteBar is not valid in the select list because it is not contained in the aggregate function or in the GROUP BY clause.