Solved

How do I add a Running Total and Historical Dates from a transaction table using SQL?

Posted on 2010-08-24
18
277 Views
Last Modified: 2012-05-10
Hi,

I've run into an issue that I can't figure out a solution for. I have a table called 'Transactions' that has account number, transaction date and amount. The account number is not unique - it can be entered multiple times with various dates and/or amounts. What I need is to take this 'Transactions' table and create a new table that will have the account number, a running total of the amount and the month the transaction occurred. Then I need that record repeated for each month after that until the next transaction for that account number occurs. I would then need this transaction's amount added to the running total and the month it occurs and then repeated until the next transaction and so forth continuing through the current month. The table has too many records to try to do this manually. I am attaching a spreadsheet that shows an example of what I have and then what I need it to do. Any help would be greatly appreciated as I am completely stuck! Running-Total.xls
0
Comment
Question by:uga_godawgs
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 7
  • 2
18 Comments
 
LVL 4

Expert Comment

by:MSSystems
ID: 33513068
How offen will you query the data?
One can do it with a table but,  Instead of duplicating the data. Have you consider a function that returns a temp table with the required results?
0
 

Author Comment

by:uga_godawgs
ID: 33513155
Unfortunately, this will be done every month. The table was originally designed to hold transactions only in new instances, however we have a need to now see it as a historical - basically, taking a "snapshot" of what happened at the end of each month. I'm not sure a function would work - maybe? - except that I need this data in a usable table that can match to an existing "snapshot" table that we have and I'm the only one in the group who has access to run SQL code.
0
 
LVL 4

Expert Comment

by:MSSystems
ID: 33513285
Will get back to you shortly
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 41

Expert Comment

by:ralmada
ID: 33513372
You don't need a function, you can do this with CTE.
Check the below: (please adjust your columns and tables names accordingly)
 

;with CTE as (
	select *, row_number() over (partition by [Account Number] order by [Transaction Date]) rn
	from yourtable
),
cTE2 as (
	select 	[Account Number], 
		dateadd(m, datediff(m, 0, [Transaction Date]), 0) as tdate, 
		dateadd(m, datediff(m, 0, getdate()), 0) as mdate
	from CTE
	where rn = 1
	union all
	select [Account Number], dateadd(m, 1, tdate), mdate
	from CTE 
	where dateadd(m, 1, tdate) < mdate
)
select 	a.[Account Number], 
	a.tdate as [month of transaction], 
	(select sum(amount) from yourtable where [Account Number] = a.[Account Number] and [Transaction Date] < dateadd(m, 1, tdate)) as Rtotal
from CTE2 a

Open in new window

0
 

Author Comment

by:uga_godawgs
ID: 33513474
Ralmada,

Just tried your code after adjusting the columns and tables. Received an error stating "row_count is not a recognized function name". I'm not sure if that's because I'm using 2005 and it's not supported or if it's because IT has limited my access to certain functions.
0
 

Author Comment

by:uga_godawgs
ID: 33513486
Sorry - meant to say "row_number" not "row_count"
0
 
LVL 41

Expert Comment

by:ralmada
ID: 33513613
even if you are in SSMS 2005, your database might not be compatible with SQL 2005 or above functions. use this
sp_dbcmptlevel 'yourdatabasename'
to check the compatibility level. It has to be 90 or over to be ok.
If not, ask if you can adjust your it to level 90 by using the following command:
sp_dbcmptlevel 'DatabaseName', 90
0
 

Author Comment

by:uga_godawgs
ID: 33513641
I'm at 80. Ran the second piece and got the following:

Valid values of database compatibility level are 60, 65, 70, or 80.
0
 
LVL 41

Expert Comment

by:ralmada
ID: 33513781
ok, that means that your database is SQL 2000 compatible, not 2005. Check the following link to see if you can adjust to sql 2005.
http://social.msdn.microsoft.com/forums/en-US/sqlsetupandupgrade/thread/4f249fc9-fcf5-4475-9ba0-c6126ce7605c 
0
 
LVL 41

Expert Comment

by:ralmada
ID: 33513946
If not you can use this alternative.
Create a number table with the following

create enum_table (number int identity, col1 int)
insert enum_table
select 1
go 20000
and then run the following script:
 

select t1.[Account Number]
	dateadd(m, tdate, 0) as tdate
into #tem
from (
	select 	[Account Number], 
		datediff(m, 0, [Transaction Date]) as tdate, 
		datediff(m, 0, getdate()) as mdate
	from yourtable a
	where [Transaction Date] = (select min([Transaction Date]) from yourtable where [Account Number] = a.[Account Number])
) t1
cross join (select number from enum_table) t2
where t2.number between t1.tdate and t2.mdate



select 	t1.[Account Number],
	t1.tdate,
	(select sum(amount) from yourtable where [Account Number] = t1.[Account Number] and [Transaction Date] < dateadd(m, 1, t1.tdate)) as Rtotal
from #tem t1

drop table #tem

Open in new window

0
 
LVL 41

Expert Comment

by:ralmada
ID: 33513957
sorry typo in the creation of the enum table
create table enum_table (number int identity, col1 int)
insert enum_table
select 1
go 20000
0
 
LVL 41

Expert Comment

by:ralmada
ID: 33514033
typo again

create table enum_table (number int identity, col1 int)
go --this is very important.
insert enum_table
select 1
go 20000  
0
 
LVL 41

Expert Comment

by:ralmada
ID: 33514095
and the first query should be
dateadd(m, t2.number, 0) as tdate ....
So here we go again:
1) Create the enum_table
create table enum_table (number int identity, col1 int)
go --this is very important.
insert enum_table
select 1
go 20000  
2)

select t1.[Account Number],
	dateadd(m, t2.number, 0) as tdate
into #tem
from (
	select 	[Account Number], 
		datediff(m, 0, [Transaction Date]) as tdate, 
		datediff(m, 0, getdate()) as mdate
	from yourtable a
	where [Transaction Date] = (select min([Transaction Date]) from yourtable where [Account Number] = a.[Account Number])
) t1
cross join (select number from enum_table) t2
where t2.number between t1.tdate and t2.mdate

select 	t1.[Account Number],
	t1.tdate,
	(select sum(amount) from yourtable where [Account Number] = t1.[Account Number] and [Transaction Date] < dateadd(m, 1, t1.tdate)) as Rtotal
from #tem t1

Open in new window

0
 

Author Comment

by:uga_godawgs
ID: 33514388
Tried it - got:

Msg 207, Level 16, State 3, Line 1
Invalid column name 'mdate'.
0
 
LVL 41

Accepted Solution

by:
ralmada earned 500 total points
ID: 33514453
wrong alias there
select t1.[Account Number],
	dateadd(m, t2.number, 0) as tdate
into #tem
from (
	select 	[Account Number], 
		datediff(m, 0, [Transaction Date]) as tdate, 
		datediff(m, 0, getdate()) as mdate
	from yourtable a
	where [Transaction Date] = (select min([Transaction Date]) from yourtable where [Account Number] = a.[Account Number])
) t1
cross join (select number from enum_table) t2
where t2.number between t1.tdate and t1.mdate

Open in new window

0
 

Author Comment

by:uga_godawgs
ID: 33514494
Works fantastic! Exactly what I needed! Thanks for your help!
0
 

Author Closing Comment

by:uga_godawgs
ID: 33514500
Thanks again!
0
 
LVL 41

Expert Comment

by:ralmada
ID: 33514535
you're welcome! Glad to help! :)
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

696 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