I created a piece of SQL using a cursor to get some values from a table, however it's incredibly inefficient and takes quite a while to execute. I need to use the results for an SSRS candlestick graph, so I need to collect the min value, max value, and open and close values, however I'm not very familiar with SQL and need to optimize. The data in the table gets a new timestamp and pipelinecount every 5 minutes. Here's the code I have so far:
declare
@min int,
@max int,
@open int,
@close int,
@date date
create table ##Candle
(
    MinVal int,
    MaxVal int,
    OpenVal int,
    CloseVal int,
    CalDate date
)
DECLARE C1 CURSOR LOCAL FOR SELECT CONVERT(date,TimeCollected) as CalendarDate from data.PipelineCount where TimeCollected > dateadd(mm,-1,CONVERT(date,GETDATE())) order by CalendarDate;
OPEN C1;
FETCH NEXT FROM C1 INTO @date;
WHILE @@FETCH_STATUS = 0
BEGIN
    select
    @min = min(PipelineCount),
    @max = max(PipelineCount)
    from data.PipelineCount
    where convert(date,TimeCollected) = @date;
    select top 1
    @open = PipelineCount
    from data.PipelineCount
    where convert(date,TimeCollected) = @date and datepart(hour,TimeCollected) = 8;
    select top 1
    @close = PipelineCount
    from data.PipelineCount
    where convert(date,TimeCollected) = @date and datepart(hour,TimeCollected) = 17;
    insert into ##Candle values(@min,@max,@open,@close,@date);
FETCH NEXT FROM C1 INTO @date;
END
CLOSE C1;
DEALLOCATE C1;
Anyone have any ideas to help?
 
     
    