Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Running totals

Author  Topic 

dmilam
Posting Yak Master

185 Posts

Posted - 2010-11-04 : 17:26:34
I'm trying to calculate the running total of a table whose initial total value can only be 0.



create table #prod (
CustomerID int not null,
Pos int not null,
Total int not null default 0
)

insert #prod

select distinct c.id as "CustomerID", Pos = 1, Total = 0
from demographics d inner join persons c on d.id = c.id
where d.code in ("X","Y")
and d.type = "foo"
and d.begindate >= "01-Jan-2007"


insert #prod

select distinct c.id as "CustomerID", Pos = 2, Total = (select count(CustomerID) from #prod where Pos = 1)
from demographics d inner join persons c on d.id = c.id
inner join delivered m on m.id = c.id
where d.code in ("X","Y")
and d.type = "foo"
and m.yr >= 2007



I'd like to see the results aligned to their position (pos), rather than offset, as here:



Total Pos
----------- -----------
0 1
3739 2



Pos 1 should have 3739 since that is the total of that select block, Pos 2 should have its quantity, unseen here. How to alter or update the table to reflect the desired result set?



Total Pos
----------- -----------
3739 1
5343 2


dmilam
Posting Yak Master

185 Posts

Posted - 2010-11-04 : 17:40:57
The sample data is not really running anywhere :-) Perhaps an analytical function or recursive CTE would do.
Go to Top of Page

Vinnie881
Master Smack Fu Yak Hacker

1231 Posts

Posted - 2010-11-04 : 19:46:13
Please provid more sample data. I am not following you exactly.


Success is 10% Intelligence, 70% Determination, and 22% Stupidity.
\_/ _/ _/\_/ _/\_/ _/ _/- 881
Go to Top of Page

dmilam
Posting Yak Master

185 Posts

Posted - 2010-11-04 : 20:41:40
This is a production code problem so I can't expand on the sample, unfortunately. I might need another table instead of trying to force the results into the temp table noted.
Go to Top of Page
   

- Advertisement -