Calculating Running Totals for Today and Today Last Year

  • I'm trying to calculate a running total for today and today last year. Here's what I use for today last year:

    DECLARE @TodayLastYear AS Date

    SET @TodayLastYear = (SELECT dateadd(yy,-1,getdate())

    Below is some sample data. I need a running total of "Int" in [Stat] for today vs. today last year. And I need the output to not contain NULLs. Also, I need to add one year to last year's date in order to match the two dates together. Since that probably makes no sense here is a sample output 🙂

    Date TotalThisYr TotalLastYr RunningTotalThisYr RunningTotalLastYr

    1-3-2013 1 1 1 1

    1-6-2013 0 1 1 2

    1-7-2013 1 0 2 2

    1-13-2013 2 0 4 2

    1-15-2013 0 1 4 3

    CREATE TABLE t

    (

    IDVARCHAR(25)NOT NULL,

    StatVARCHAR(25)NOT NULL,

    StatDateDATENOT NULL

    );

    INSERT INTO t

    (

    ID, Stat, StatDate

    )

    Values

    ('1', 'Int', '2012-01-03'),

    ('2', 'Int', '2012-01-06'),

    ('3', 'Int', '2012-01-15'),

    ('4', 'Int', '2012-02-07'),

    ('5', 'Int', '2013-01-03'),

    ('6', 'Int', '2013-01-07'),

    ('7', 'Int', '2013-01-13'),

    ('8', 'Int', '2013-01-13'),

    ('9', 'Sec', '2012-01-06'),

    ('10', 'Sec', '2013-02-01')

  • 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

  • Thanks again, Dwain. That is super helpful. I was inner joining on the date column, and while it didn't leave NULLs, it also kicked out several rows (whereas my left join left a landscape of scattered NULLs). So this should do the trick. Thanks!

  • DataAnalyst011 (2/1/2013)


    Thanks again, Dwain. That is super helpful. I was inner joining on the date column, and while it didn't leave NULLs, it also kicked out several rows (whereas my left join left a landscape of scattered NULLs). So this should do the trick. Thanks!

    The next question would be, do you actually and fully understand how it works?

    --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)

  • Hi Jeff,

    Thanks for commenting. At this point I don't, but I haven't put Dwain's code in production. One of my principles of the help I get on this forum is to never put a line of code in production I don't completely understand. I could envision such a thing going really bad at some point.

    (As a side note the only exception I've made to that rule is median-of-quartile calculation that Dwain helped me with a couple of days ago. I can follow everything he did but CROSS APPLY. I've read 6 articles and still don't quite get it! But I absolutely had to have a the median-of-quartile calculations to create an SSRS chart for a one-off presentation. Since I could hand verify the accuracy of the data from other reports I've written, I did a single run. But now that code is offline until I can play with CROSS APPLY enough to understand it. That's the only exception I remember.)

    Generally I always ask follow-up questions regarding how examples work on anything that is above my pay grade. There is a "how'd you do that" reply in probably 3 out of every 4 posts I start - and some I don't! However, since Dwain helped me so much on the recent post, I felt bad asking. So I've been working through the linked article, and on Monday I'll start working through his code in my test environment (I had to back off the project yesterday and today to pull data for a last minute request for our board of trustee meeting).

    Would you mind explaining it to me? I understand the temp table and the insertion of the SUM'd data from the subquery in the FROM clause. But I get lost with some of the details in subquery, and after he declares the two variables its all downhill 🙂 The code looks great, I just get lost at that point. Either way, I'll continue working through the article and reading adding explanations. But having my test example explained would probably speed up my understanding!

  • One of my principles of the help I get on this forum is to never put a line of code in production I don't completely understand.

    That's absolutely the correct spirit!

    I believe the best thing for now would be for you to read the linked article. It explains a whole lot that I would only be regurgitating here. If after reading it, you still have questions about how it works, then c'mon back and we'll do our darnest to explain it. I guess the simplest explanation is that it works pretty much the same way that you'd do a running total in a spreadsheet without using the SUM() function.

    --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)

  • Jeff Moden (2/2/2013)


    One of my principles of the help I get on this forum is to never put a line of code in production I don't completely understand.

    That's absolutely the correct spirit!

    I believe the best thing for now would be for you to read the linked article. It explains a whole lot that I would only be regurgitating here. If after reading it, you still have questions about how it works, then c'mon back and we'll do our darnest to explain it. I guess the simplest explanation is that it works pretty much the same way that you'd do a running total in a spreadsheet without using the SUM() function.

    I'll second Jeff's comment. The article provides the most comprehensive explanation of the rules around the QU that I've ever seen. Pay particular attention to the CLUSTERED PRIMARY KEY on the temp table and OPTION (MAXDOP) hint on the query, both of which are explained in the article, because those two items are the key to making it work.


    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

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply