Groups | Blog | Home
all groups > sql server programming > april 2007 >

sql server programming : Running Total for sales by week


aj70000 NO[at]SPAM hotmail.com
4/25/2007 11:11:08 PM
Hi,

Here's what I need as the output for running total


Week BU Cumulative_Amount
1 AB 100
2 AC 230
3 AB 120
4 AB 0
5 AB 120

I would like to fill in the value of week 4 to 120 using a sql
statement.

Thoughts?

AJ
Immy
4/26/2007 7:17:30 AM
without looking at your data its hard to tell, but you can use CASE/COALESCE
function.
i.e. CASE when 0 then 120 etc...
[quoted text, click to view]

M A Srinivas
4/26/2007 8:22:38 AM
[quoted text, click to view]

This is a sample to work along what you require

declare @tbla table (weekno int ,bu varchar(5),amount int)
insert into @tbla values(1,'AB',100)
insert into @tbla values(2,'AB',150)
insert into @tbla values(3,'AB',-250)
insert into @tbla values(4,'AB',120)
insert into @tbla values(1,'AC',230)
insert into @tbla values(2,'AC',160)

select weekno,bu,
(select sum(amount)
from @tbla b
where a.bu = b.bu
and a.weekno >= b.weekno) as cumulative_amount
from @tbla a
order by bu,weekno
AddThis Social Bookmark Button