Click here to Skip to main content
15,909,466 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi,
I am having trouble writing a query that accurately does what I need.
I have a table like the following
Id    Date        Value     Cumulative
1     Jan 1st       0.2
2     Jan 1st       0.5
1     Jan 2nd       0.7
2     Jan 2nd       0.6
4     Jan 2nd       0.1
1     Jan 3rd       0.02
3     jan 3rd      0.01
4     Jan 3rd      0.03


I want to write a query which inserts the cumulative column with the sum of the value for the same Ids i.e.,
Id     Cumulative
1        0.2
2        0.5
1        0.9  (0.2+0.7)
2        1.1  (0.5+0.6)
4        0.1
1        0.92  (0.2+0.7+0.02)
3        0.01
4        0.13  (0.1 + 0.03)


Thanks in advance.
Posted
Updated 28-Aug-11 18:52pm
v2
Comments
Prerak Patel 29-Aug-11 0:54am    
If you are having table like this, you need to consider the redesign.

1 solution

It would be easy if you have an additional sequence column (e.g. UniqeID). If you have, you can just have it this way

SQL
Update CumulativeTable
    SET Cumulative = Value + (Select Sum(Value) From CumulativeTable Where UniqueID < c.UniqueID
                        AND ID = c.ID)
From CumulativeTable c


or if you don't have, you can try this,


SQL
DECLARE @TempTable TABLE (UniqueID int IDENTITY,
ID int,
Value numeric(18,3),
Cumulative numeric(18,3)
)

DECLARE @TempTable TABLE (UniqueID int IDENTITY,
ID int,
Value numeric(18,3),
Cumulative numeric(18,3)
)

Insert Into @TempTable (ID, Value, Cumulative)
Select ID, Value, Cumulative From CumulativeTable

Update CumulativeTable
	SET Cumulative = COALESCE(c.Value + (Select Sum(Value) From @TempTable Where UniqueID < c.UniqueID
						AND ID = c.ID),0)
From CumulativeTable t, @TempTable c
Where t.ID = c.ID AND t.Value = c.Value



but this will not give you correct value if you have multiple records with the same ID and value
 
Share this answer
 
Comments
Ananth Ramchandran 29-Aug-11 10:30am    
Than you for your response.But I have a doubt.In the first query if what is c in c.UniqueId??? Is it the cumulative table??

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900