• Hello again DA!

    QU is the fastest approach for running totals:

    CREATE TABLE #t2

    (StatDate DATE PRIMARY KEY CLUSTERED

    ,TotalThisYr INT

    ,TotalLastYr INT

    ,RunningTotalThisYr INT

    ,RunningTotalLastYr INT)

    INSERT INTO #t2

    SELECT StatDate, TotalThisYr=SUM(TotalThisYr)

    ,TotalLastYr=SUM(TotalLastYr)

    ,RunningTotalThisYr=SUM(RunningTotalThisYr)

    ,RunningTotalLastYr=SUM(RunningTotalLastYr)

    FROM (

    SELECT StatDate, TotalThisYr=1, TotalLastYr=0

    ,RunningTotalThisYr=0, RunningTotalLastYr=0

    FROM t a

    WHERE YEAR(StatDate) = 2013 AND Stat = 'Int'

    UNION ALL

    SELECT DATEADD(year, 1, a.StatDate), 0, 1, 0, 0

    FROM t a

    WHERE YEAR(StatDate) = 2012 AND Stat = 'Int') a

    GROUP BY StatDate

    ORDER BY a.StatDate

    DECLARE @ThisYr INT = 0, @LastYr INT = 0

    UPDATE #t2

    SET @ThisYr = @ThisYr + TotalThisYr

    ,@LastYr = @LastYr + TotalLastYr

    ,RunningTotalThisYr = @ThisYr

    ,RunningTotalLastYr = @LastYr

    OPTION (MAXDOP 1);

    SELECT *

    FROM #t2

    Read this article for more info on QU: http://www.sqlservercentral.com/articles/T-SQL/68467/


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St