Solved

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

Posted on 2010-08-24
18
244 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
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 
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

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

911 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

17 Experts available now in Live!

Get 1:1 Help Now