Solved

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

Posted on 2010-08-24
18
236 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
  • 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
 
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
MS SQL export CSV & schedule It 9 44
ms sql stored procedure 22 77
how to fix this error 14 48
Access recordset not updateable 8 39
Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
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.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

746 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now