views:

242

answers:

3

Hi

I have table with columns as

      Operation             Cost

     Material Issue         10 
     Material Return        20
     X                      30
     Y                      40
     Z                      50

I want want a query where columns are

     Operation             Cost    Total

     Material Issue         10      10
     Material Return        20      30
     X                      30      60
     Y                      40      100
     Z                      50      150

ie.., the the total should keep on adding with each row of cost Column

A: 

See this post about Running Counts

Colin
that's not solve the problem
KuldipMCA
just saying that it doesn't solve the problem isn't helpful. you should also state what's wrong with it.
Mladen Prajdic
+2  A: 

try this

DECLARE @Table TABLE(
     ID INT IDENTITY(1,1),
     Descr VARCHAR(20),
     Val FLOAT
)

INSERT INTO @Table (Descr,Val) SELECT 'X', 10
INSERT INTO @Table (Descr,Val) SELECT 'Y', 20
INSERT INTO @Table (Descr,Val) SELECT 'Z', 50
INSERT INTO @Table (Descr,Val) SELECT 'A', 75
INSERT INTO @Table (Descr,Val) SELECT 'B', 100

SELECT  t1.Descr,
     t1.Val,
     SUM(ISNULL(t2.Val,0))
FROM    @Table t1 LEFT JOIN
     @Table t2 ON t1.ID >= t2.ID
GROUP BY    t1.Descr,
      t1.Val
astander
A: 

There are different ways to calculate running totals. This article on SQLTeam covers them and will help you get your query done. The code examples there are easy adaptable, so I let you choose the one which best fits your needs.

MicSim