I have a Table that stores data on price movement over a minute. Each record contains the last Minute’s Open, High, Low, Close & Volume
CREATE TABLE TimeBar (
Instrument varchar(20),
BarTimeStamp datetimeoffset(7),
Open decimal(18, 5),
High decimal(18, 5),
Low decimal(18, 5),
Close decimal(18, 5),
Volume int
)
What I am trying to do is create a query where I can aggregate the data into higher time frames, for example I want to be able to Show the Open, High, Low & Close for each Hour.
Below is my query so far, I have managed to get the High and The Low, but how do you get the Open and The Close?
SELECT MIN(BarTimeStamp) AS TimeStamp,
MAX(High) AS High,
MIN(Low) AS Low,
SUM(Volume) AS Volume
FROM TimeBar
WHERE Instrument = 'XYZ'
GROUP BY DATEPART(YEAR, BarTimeStamp), DATEPART(MONTH, BarTimeStamp), DATEPART(DAY, BarTimeStamp), DATEPART(HOUR, BarTimeStamp)
Use the main query as a subquery, taken for each record the min timestamp and max timestamp, and so, take the respective open and close prices for them.