• MyDoggieJessie (3/7/2014)


    To add to SQLCJ's post, you will need to include the ORDER BY date_value at the end to get the OP's expected result - and some ugly string manipulation for the date

    SELECT CONVERT(CHAR(4), GETDATE(), 120) + ' ' + CONVERT(CHAR(4), GETDATE(), 100) ,

    monthly_total ,

    ( SELECT SUM(monthly_total)

    FROM #sales s

    WHERE date_value <= tst.date_value

    ) AS monthly_total

    FROM ( SELECT * ,

    ROW_NUMBER() OVER ( ORDER BY date_value ) tst

    FROM #sales

    ) tst

    ORDER BY date_value A

    Ah, be carefull now. That contains an (X2+X)/2+X Triangular join. In this case, it generates 324 internal rows for the 24 original rows. While it "runs fast" for such a small quantity of rows, these things can be server killers. With just 10,000 original rows, SQL Server will generate 50,015,000 internal rows and all of the logical reads to go with it. A cursor and WHILE loop or a Recursive CTE would actually run much faster.

    Please see the following article about "Triangular Joins" for more information.

    http://www.sqlservercentral.com/articles/T-SQL/61539/

    OR... if you follow the rules, there's a bit of undocumented code known at the "Quirky Update". If you don't follow the rules, it can bite ya. It will, however, do a million row running or grouped running total in just seconds and is faster than even the new methods in SQL Server 2012. Plese see the following article for that.

    http://www.sqlservercentral.com/articles/T-SQL/68467/

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)