## Calculating Running Totals for Today and Today Last Year

 Author Message DataAnalyst011 SSCommitted Group: General Forum Members Points: 1976 Visits: 530 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 SSC-Forever Group: General Forum Members Points: 44123 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 SSCommitted Group: General Forum Members Points: 1976 Visits: 530 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 Guru Group: General Forum Members Points: 506731 Visits: 44268 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.If you think its expensive to hire a professional to do the job, wait until you hire an amateur. -- Red Adair Helpful Links:How to post code problemsHow to post performance problemsForum FAQs DataAnalyst011 SSCommitted Group: General Forum Members Points: 1976 Visits: 530 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 Guru Group: General Forum Members Points: 506731 Visits: 44268 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.If you think its expensive to hire a professional to do the job, wait until you hire an amateur. -- Red Adair Helpful Links:How to post code problemsHow to post performance problemsForum FAQs dwain.c SSC-Forever Group: General Forum Members Points: 44123 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

## Permissions

 You can't post new topics. You can't post topic replies. You can't post new polls. You can't post replies to polls. You can't edit your own topics. You can't delete your own topics. You can't edit other topics. You can't delete other topics. You can't edit your own posts. You can't edit other posts. You can't delete your own posts. You can't delete other posts. You can't post events. You can't edit your own events. You can't edit other events. You can't delete your own events. You can't delete other events. You can't send private messages. You can't send emails. You can read topics. You can't vote in polls. You can't upload attachments. You can download attachments. You can't post HTML code. You can't edit HTML code. You can't post IFCode. You can't post JavaScript. You can post emoticons. You can't post or upload images.

##### Select a forum
 SQL Server 2017      SQL Server 2017 - Administration      SQL Server 2017 - Development SQL Server 2016      SQL Server 2016 - Administration      SQL Server 2016 - Development and T-SQL SQL Server 2014      Administration - SQL Server 2014      Development - SQL Server 2014 SQL Server 2012      SQL 2012 - General      SQL Server 2012 - T-SQL SQL Server vNext      SQL Server 15 - Administration      SQL Server 15 - Development SQL Server 2008      SQL Server 2008 - General      T-SQL (SS2K8)      June 2007 CTP      Working with Oracle      July CTP      SQL Server Newbies      Security (SS2K8)      SQL Server 2008 High Availability      SQL Server 2008 Administration      Data Corruption (SS2K8 / SS2K8 R2)      SQL Server 2008 Performance Tuning Cloud Computing      SQL Azure - Development      SQL Azure - Administration      Amazon AWS and other cloud vendors      General Cloud Computing Questions      CosmosDB      Azure Data Lake      Azure Machine Learning Reporting Services      Reporting Services      Reporting Services 2005 Administration      Reporting Services 2005 Development      Reporting Services 2008/R2 Administration      Reporting Services 2008 Development      SSRS 2012      SSRS 2014      SSRS 2016 Programming      Connecting      General      SMO/RMO/DMO      XML      Service Broker      Powershell      Testing      TFS/Data Dude/DBPro      SSDT      Continuous Integration, Deployment, and Delivery      R Services and R Language Data Warehousing      Integration Services      Strategies and Ideas      Analysis Services      Data Transformation Services (DTS)      Performance Point      Data Mining      PowerPivot      R language      Machine Learning Database Design      Disaster Recovery      Design Ideas and Questions      Relational Theory      Hardware      Virtualization      Security and Auditing SQLServerCentral.com      Anything that is NOT about SQL!      Contests!      Editorials      SQLServerCentral.com Announcements      SQLServerCentral.com Website Issues      Suggestions      Tag Issues with Content      Podcast Feedback      SQLServerCentral.com Test Forum      Articles Requested SQL Server 2005      Administering      Backups      Business Intelligence      CLR Integration and Programming.      Data Corruption      Development      Working with Oracle      SQL Server 2005 Compact Edition      SQL Server 2005 General Discussion      SQL Server 2005 Security      SQL Server 2005 Strategies      SS2K5 Replication      SQL Server Express      SQL Server 2005 Performance Tuning      SQL Server 2005 Integration Services      T-SQL (SS2K5)      SQL Server Newbies SQL Server 7,2000      Administration      Backups      Data Corruption      General      Globalization      In The Enterprise      Working with Oracle      Security      Strategies      SQL Server Newbies      Service Packs      SQL Server CE      Performance Tuning      Replication      Sarbanes-Oxley      T-SQL      SQL Server Agent SQL Server and other platforms      MySQL      Oracle      PostgreSQL      DB2      SQL Server and Sharepoint Older Versions of SQL (v6.5, v6.0, v4.2)      Older Versions of SQL (v6.5, v6.0, v4.2) Career      Certification      Employers and Employees      Events      Job Postings      Resumes and Job Hunters      Presentations and Speaking      Retired Members Testing Center      SQL Server Security Skills      Question of the Day (QOD) Microsoft Access      Microsoft Access Products and Books      Third Party Products         SQLCentric         Extreme Technologies.         Innovartis         Embarcadero         SQL Sentry         Sonasoft         Golden Gate Software         Idera         Lumigent         Red Gate Software         ApexSQL         Quest Software         CA      Discussions about Books         Discuss Programming Books          Discuss XML Books          Discuss T-SQL Books          Discuss Data Warehousing Books          Discuss DTS Books          Discuss SQL Server 2000 Books         Discuss SQL Server 7.0 Books Notification Services      Administration Article Discussions Future Versions      SQL 12