Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

SQL Update column as running balance

Posted on 2014-03-12
4
Medium Priority
?
584 Views
Last Modified: 2014-03-12
I have a table - TRANSACTIONS that has columns AGREEMENTID, TRANSACTIONDATE, OrigInventoryCost, InventoryCostBalance.  I need the InventoryCostBalance updated to be a running total of OrigInventoryCost.  Right Now, the InventoryCostBalance is all zeroes.

Here is a small sampling of what it should look like.

AgreementID    TRANSACTIONDATE  OrigInventoryCost   InventoryCostBalance (should be)
1                         07/09/13 08:00:00                     299.99                     299.99
1                         07/09/13 08:01:00                      -25.00                     274.99
1                         08/09/13 08:00:00                      -25.00                     249.99

I cannot use a CURSOR as there are upwards of 2 million records now and many added daily.   I can handle the daily additions, but cannot seem to get the table updated with current records.

Does anyone know how to get the data updated properly?
0
Comment
Question by:lburnsinmagnolia
  • 2
  • 2
4 Comments
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 2000 total points
ID: 39923482
step 1: ensure you have a (clustered) index on AgtreementID + TransactionDate

step 2: run this code
UPDATE t
   SET InventoryCostBalance  = ( SELECT SUM(h,OrigInventoryCost)
                   FROM TRANSACTIONS h
                   WHERE h.AgreementID  = t.AgreementID    
                       AND h.TRANSACTIONDATE <= t.TRANSACTIONDATE  
          )
  FROM TRANSACTIONS  t 

Open in new window

0
 

Author Comment

by:lburnsinmagnolia
ID: 39923918
I have tried that, the problem is that since it's a running total, the only row that gets updated is the very next row.  All subsequent rows have the same InventoryCostBalance as the second row.  So in my sample above, the 3rd row is set to 274.99 and if there are more rows, they too would be 274.99

Since the Primary key is clustered (identity column), I cannot create a clustered index.  I have a nonclustered one on the agreementid, transactiondate.
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 39923954
I admit I have a typo in my above code, inside the SUM() function it should be "." and not ",".

apart from that, the code works correctly, tested:
declare @transactions table ( AgreementID    int , TRANSACTIONDATE  datetime, OrigInventoryCost  decimal(10,2), InventoryCostBalance decimal(10,2))
insert into @transactions ( AgreementID    , TRANSACTIONDATE, OrigInventoryCost)
select 1, getdate()-1, 299.99
insert into @transactions ( AgreementID    , TRANSACTIONDATE, OrigInventoryCost)
select 1, dateadd(minute, 1, getdate()-1 ), -25
insert into @transactions ( AgreementID    , TRANSACTIONDATE, OrigInventoryCost)
select 1, dateadd(minute, 10, getdate()-1 ), -25

update t  
SET InventoryCostBalance  = ( SELECT SUM(h.OrigInventoryCost)
                   FROM    @transactions  h
                   WHERE h.AgreementID  = t.AgreementID    
                       AND h.TRANSACTIONDATE <= t.TRANSACTIONDATE  
          )
  from @transactions t

  select * from @transactions 

Open in new window

output is:

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(3 row(s) affected)

AgreementID TRANSACTIONDATE         OrigInventoryCost                       InventoryCostBalance
----------- ----------------------- --------------------------------------- ---------------------------------------
1           2014-03-11 17:00:49.533 299.99                                  299.99
1           2014-03-11 17:01:49.533 -25.00                                  274.99
1           2014-03-11 17:10:49.533 -25.00                                  249.99

(3 row(s) affected)

Open in new window


if it does "not work" for you, the first guess I would make is that the transaction_date field is not datetime, but varchar?
0
 

Author Comment

by:lburnsinmagnolia
ID: 39924082
That worked!  It works without an index, but takes longer.  I will correct that.

Thanks!
0

Featured Post

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction: When running hybrid database environments, you often need to query some data from a remote db of any type, while being connected to your MS SQL Server database. Problems start when you try to combine that with some "user input" pass…
Data architecture is an important aspect in Software as a Service (SaaS) delivery model. This article is a study on the database of a single-tenant application that could be extended to support multiple tenants. The application is web-based develope…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…

926 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question