Вы хотите анализировать данные с интервалами в 5 минут. Вы можете использовать оконные функции со следующим предложением разделения:
partition by datepart(year, t.[time]),
datepart(month, t.[time]),
datepart(day, t.[time]),
datepart(hour, t.[time]),
(datepart(minute, t.[time]) / 5)
Запрос:
select *
from (
select
t.time,
row_number() over(
partition by datepart(year, [time]),
datepart(month, [time]),
datepart(day, [time]),
datepart(hour, [time]),
(datepart(minute, [time]) / 5)
order by [time]
) [rn],
first_value([open]) over(
partition by datepart(year, [time]),
datepart(month, [time]),
datepart(day, [time]),
datepart(hour, [time]),
(datepart(minute, [time]) / 5)
order by [time]
) [open],
last_value([close]) over(
partition by datepart(year, [time]),
datepart(month, [time]),
datepart(day, [time]),
datepart(hour, [time]),
(datepart(minute, [time]) / 5)
order by [time]
) [close],
max([high]) over (
partition by datepart(year, [time]),
datepart(month, [time]),
datepart(day, [time]),
datepart(hour, [time]),
(datepart(minute, [time]) / 5)
) [high],
min([low]) over (
partition by datepart(year, [time]),
datepart(month, [time]),
datepart(day, [time]),
datepart(hour, [time]),
(datepart(minute, [time]) / 5)
) [low],
avg([volume]) over (
partition by datepart(year, [time]),
datepart(month, [time]),
datepart(day, [time]),
datepart(hour, [time]),
(datepart(minute, [time]) / 5)
) [volume]
from mytable t
) t
where rn = 1