## Calculating Running Totals for Today and Today Last Year

 Author Message DataAnalyst011 SSC-Enthusiastic Group: General Forum Members Points: 112 Visits: 426 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 DateSET @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 RunningTotalLastYr1-3-2013 1 1 1 11-6-2013 0 1 1 21-7-2013 1 0 2 21-13-2013 2 0 4 21-15-2013 0 1 4 3``CREATE TABLE t( ID VARCHAR(25) NOT NULL, Stat VARCHAR(25) NOT NULL, StatDate DATE NOT 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')` dwain.c SSCarpal Tunnel Group: General Forum Members Points: 4253 Visits: 6431 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 #t2SELECT 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') aGROUP BY StatDateORDER BY a.StatDateDECLARE @ThisYr INT = 0, @LastYr INT = 0UPDATE #t2SET @ThisYr = @ThisYr + TotalThisYr ,@LastYr = @LastYr + TotalLastYr ,RunningTotalThisYr = @ThisYr ,RunningTotalLastYr = @LastYrOPTION (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!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?Since random numbers are too important to be left to chance, let's generate some!Learn to understand recursive CTEs by example.Splitting strings based on patterns can be fast!My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables DataAnalyst011 SSC-Enthusiastic Group: General Forum Members Points: 112 Visits: 426 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! Jeff Moden SSC-Forever Group: General Forum Members Points: 45071 Visits: 39906 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 ModenRBAR 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.Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.Although change is inevitable, change for the better is not.Just because you can do something in PowerShell, doesnt mean you should. Helpful Links:How to post code problemsHow to post performance problemsForum FAQs DataAnalyst011 SSC-Enthusiastic Group: General Forum Members Points: 112 Visits: 426 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! Jeff Moden SSC-Forever Group: General Forum Members Points: 45071 Visits: 39906 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 ModenRBAR 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.Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.Although change is inevitable, change for the better is not.Just because you can do something in PowerShell, doesnt mean you should. Helpful Links:How to post code problemsHow to post performance problemsForum FAQs dwain.c SSCarpal Tunnel Group: General Forum Members Points: 4253 Visits: 6431 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!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?Since random numbers are too important to be left to chance, let's generate some!Learn to understand recursive CTEs by example.Splitting strings based on patterns can be fast!My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables