Log in  ::  Register  ::  Not logged in

## Calculate the Running Total for the last five Transactions

 Author Message Divya Agrawal SSCrazy Group: General Forum Members Points: 2464 Visits: 608 Comments posted to this topic are about the item Calculate the Running Total for the last five Transactions --Divya Lynn Pettis SSC Guru Group: General Forum Members Points: 299005 Visits: 41463 Good article, but let's take another approach and see what we see.Taking your sample data from your article, and using a slightly different tact, here is another way to tackle your problem given in your article. I have included your sample data, table (with a slight modification for my code), and code as well as my code.`set nocount ongoCREATE TABLE dbo.Accounts(ID int IDENTITY(1,1) primary key, -- Primary Key defaults to a clustered index, needed for this to workTransactionDate datetime,Balance money,RunningBalance money null);goinsert into Accounts(TransactionDate,Balance) values ('1/1/2000',100);insert into Accounts(TransactionDate,Balance) values ('1/2/2000',101);insert into Accounts(TransactionDate,Balance) values ('1/3/2000',102);insert into Accounts(TransactionDate,Balance) values ('1/4/2000',103);insert into Accounts(TransactionDate,Balance) values ('1/5/2000',104);insert into Accounts(TransactionDate,Balance) values ('1/6/2000',105);insert into Accounts(TransactionDate,Balance) values ('1/7/2000',106);insert into Accounts(TransactionDate,Balance) values ('1/8/2000',107);insert into Accounts(TransactionDate,Balance) values ('1/9/2000',108);insert into Accounts(TransactionDate,Balance) values ('1/10/2000',109);insert into Accounts(TransactionDate,Balance) values ('1/11/2000',200);insert into Accounts(TransactionDate,Balance) values ('1/12/2000',201);insert into Accounts(TransactionDate,Balance) values ('1/13/2000',202);insert into Accounts(TransactionDate,Balance) values ('1/14/2000',203);insert into Accounts(TransactionDate,Balance) values ('1/15/2000',204);insert into Accounts(TransactionDate,Balance) values ('1/16/2000',205);insert into Accounts(TransactionDate,Balance) values ('1/17/2000',206);insert into Accounts(TransactionDate,Balance) values ('1/18/2000',207);insert into Accounts(TransactionDate,Balance) values ('1/19/2000',208);insert into Accounts(TransactionDate,Balance) values ('1/20/2000',209);goselect * from dbo.Accounts;goprint '-- Cross Join Query --';set statistics io onSELECT Acc.ID,CONVERT(varchar(50),TransactionDate,101) AS TransactionDate , Balance, isnull(RunningTotal,'') AS RunningTotal FROM Accounts Acc LEFT OUTER JOIN (SELECT ID,sum(Balance) AS RunningTotal FROM (SELECT A.ID AS ID,B.ID AS BID, B.Balance FROM Accounts A cross JOIN Accounts B WHERE B.ID BETWEEN A.ID-4 AND A.ID AND A.ID>4)T GROUP BY ID ) Bal ON Acc.ID=Bal.ID;set statistics io offprint '-- Cross Join Query --';goprint '-- Update Query --';set statistics io ondeclare @var1 money, @var2 money, @var3 money, @var4 money, @var5 money;update dbo.Accounts set @var5 = @var4, @var4 = @var3, @var3 = @var2, @var2 = @var1, @var1 = Balance, RunningBalance = isnull(@var1 + @var2 + @var3 + @var4 + @var5, 0);set statistics io offprint '-- Update Join Query --';goprint '-- Select After Update Query --';set statistics io onselect * from dbo.Accounts;set statistics io offprint '-- Select After Update Query --';godrop table dbo.Accounts;goset nocount offgo`My results match yours in the article, but what I also wanted to include here were the stats I also had collected using statistic io on (included in the above code).-- Cross Join Query --Table 'Accounts'. Scan count 17, logical reads 74, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.-- Cross Join Query ---- Update Query --Table 'Accounts'. Scan count 1, logical reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.-- Update Join Query ---- Select After Update Query --Table 'Accounts'. Scan count 1, logical reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.-- Select After Update Query --I'll leave further assessment of the different approaches to others. For me, I just wanted to see what might be different. Lynn PettisFor better assistance in answering your questions, click hereFor tips to get better help with Performance Problems, click hereFor Running Totals and its variations, click here or when working with partitioned tablesFor more about Tally Tables, click hereFor more about Cross Tabs and Pivots, click here and hereManaging Transaction LogsSQL Musings from the Desert Fountain Valley SQL (My Mirror Blog) Jacob Luebbers Hall of Fame Group: General Forum Members Points: 3860 Visits: 1220 @Lynn:Gold Regards,Jacob ChiragNS SSCoach Group: General Forum Members Points: 18843 Visits: 1865 Brilliant Divya and Lynn "Keep Trying" Hugo Kornelis SSC-Forever Group: General Forum Members Points: 44705 Visits: 13555 There is a huge problem with this technique. IDENTITY values are not guaranteed to be consecutive; for a variety of reasons there may be gaps. Those will invalidate the results from this query.On SQL Server 2005 and above, using ROW_NUMBER() is the adviced technique. On SQL Server 2000 and below - well, let's just say that the required query will be ugly... Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)Visit my SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis Ninja's_RGR'us SSC Guru Group: General Forum Members Points: 205560 Visits: 9673 Hugo, are you talking about the quirky update for 2000? Hugo Kornelis SSC-Forever Group: General Forum Members Points: 44705 Visits: 13555 Ninja's_RGR'us (11/27/2008)Hugo, are you talking about the quirky update for 2000?Hi Ninja's_RGR'us,No. As far as I know, UPDATE is not quirky at all in SQL Server 2000. What do you mean by "quirky update"?What I was refering too is the lack of ROW_NUMBER() in SQL Server 2000. This means you'll either have to take your chance with IDENTITY, at the risk of gaps, as the author of this article did; or you have to use a correlated subquery to calculate the row number on the fly, which can result in dramatic performance as the amount of rows grows. Plus, the queries tend to get long and hard to understand. Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)Visit my SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis Ninja's_RGR'us SSC Guru Group: General Forum Members Points: 205560 Visits: 9673 I meant this by quirky update : Update table set @Var = UpdatedColumn = @Var + WhateverIttakesToEvalutateThisVariableThis must be used with a index hint on a temp table to be sure that nothing goes wrong...That's a way to make a running total... the case statement here would be quite interesting though ;-P. Hugo Kornelis SSC-Forever Group: General Forum Members Points: 44705 Visits: 13555 Ninja's_RGR'us (11/27/2008)I meant this by quirky update : Update table set @Var = UpdatedColumn = @Var + WhateverIttakesToEvalutateThisVariableThis must be used with a index hint on a temp table to be sure that nothing goes wrong...That's a way to make a running total... the case statement here would be quite interesting though ;-P.Oohh, that one.You know that this "trick" is neither documented nor supported, do you?(Clarification: "UPDATE ... SET @var = column = expression" is documented and supported, but the effects of the same variable in the expression are not - and given the official intent of an UPDATE statement, the results people currently get in 99% of all cases could be considered a bug). Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)Visit my SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis Ninja's_RGR'us SSC Guru Group: General Forum Members Points: 205560 Visits: 9673 Yup that's the one!Thanks for the clarifications!

## 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      Question of the Day (QOD)      SQL Server Security Skills Microsoft Access      Microsoft Access Products and Books      Third Party Products         CA         SQLCentric         Extreme Technologies.         Innovartis         Embarcadero         SQL Sentry         Golden Gate Software         Idera         Lumigent         Red Gate Software         Quest Software         ApexSQL         Sonasoft      Discussions about Books         Discuss Programming Books          Discuss XML Books          Discuss Data Warehousing Books          Discuss T-SQL Books          Discuss DTS Books          Discuss SQL Server 2000 Books         Discuss SQL Server 7.0 Books Notification Services      Administration Article Discussions Future Versions      SQL 12

## Search

 Copyright © 2002-2018 Redgate. All Rights Reserved. Privacy Policy. Terms of Use. Report Abuse.