May 3, 2008 at 12:19 am
Hi All,
I have a Table with 3 columns
SalesPID SalesAmount DiscountAmount
12 120 20.00
13 130 30.00
14 140 40.00
I Need An Output Table like the Following table which contains extra column with name RunningTotals which is sum of currentRow discountAmount and Previous row of RunningTotal Value.Is it Possible to fill a temporary table or tableVariable or commonTableExpressions or using any other statements without using cursor or looping statements.
SalesPID SalesAmount DiscountAmount Running Totals
12 120 20.00 20.00
13 130 30.00 50.00
14 140 40.00 90.00
Awaiting Your Valuable Inputs
Thanks and Best Regards,
Rajesh
May 3, 2008 at 12:50 am
I don't suppose you did a search on "running total" or anything like that... 😉
There's a lot of ways to solve the running total problem in SQL Server... they're all slow in the face of any scalability... except for one... see the following URL.
http://www.sqlservercentral.com/articles/Advanced+Querying/61716/
--Jeff Moden
Change is inevitable... Change for the better is not.
May 5, 2008 at 9:56 am
Jeff' link is really thorough and provides a great explanation of the pros/cons. In the meantime, here is a simple way to solve it. Hope this helps.
declare @table table
(
salespid int
,salesamount money
,discountamount decimal
)
insert into @table select 12, 120, 20.00
insert into @table select 13, 130, 30.00
insert into @table select 14, 140, 40.00
select
outside.salespid
,outside.salesamount
,outside.discountamount
,(
select
sum(inside.discountamount)
from
@table inside
where
inside.salespid <= outside.salespid
) as runningtotal
from
@table outside
order by
3
"Any fool can write code that a computer can understand. Good programmers write
code that humans can understand." -Martin Fowler et al, Refactoring: Improving the Design of Existing Code, 1999
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply