• leesider (11/27/2012)


    OK, as I said in my last post I need to extend it a little further to include a running total. Cadavre is correct, I don't need a cursor. I need to execute an inner select from another table that also contains a startup_Time. I want to compare this startup_Time with the startup_Time in the outer select and as it goes from one week to the next, select from the column KWH_savings and add it up for each week in the inner select.

    What I have below does it except it is too slow:

    ;with cte as

    (

    SELECT [YEAR] = YEAR(st.startup_Time),

    DATEPART(ww, st.startup_Time) as WeekNumber,

    (

    SELECT SUM(st2.KWH_savings)

    FROM #KWHtemp st2

    WHERE

    st2.startup_Time <= st.startup_Time

    ) AS AccountRunningTotal

    FROM #KWHtemp st

    )

    SELECT *

    FROM cte

    It is the inner select that is slowing it down, I don't know if I can do it a different way that is not so slow.

    This is where knowing the entire problem up front would be very helpful. You don't need to do an "inner query" here as you call it. I think what you really want here is a running total. What you have done here is what is known as a triangular join and as you have discovered the performance is hideous. Take a look at this article by Jeff Moden. http://www.sqlservercentral.com/articles/T-SQL/68467/[/url]

    He explains how the running total works and how to make it fast.

    If you need help with the actual code you need to post ddl, sample data and desired output based on the article in my signature.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/