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 2008 Forums
 Transact-SQL (2008)
 SUM of previous row value

Author  Topic 

DeNam
Starting Member

15 Posts

Posted - 2013-08-23 : 03:36:35
Hi,

I want to have a field (T1.Field2) which sums the previous values of the same row and previous rows of another field (T1.Field1).

How do i code this in sql script.

Example

Field1 Field2
6 6
7 13
3 16

and so on.

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2013-08-23 : 04:30:04
Provide us the sample data and expected output.....
Is there any datetime column/autoincremented column in the table?

--
Chandu
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2013-08-26 : 07:01:54
Search for Running Total and you will find lot of related links

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

sivadss2007
Starting Member

18 Posts

Posted - 2013-08-28 : 05:08:55
This will work fine when you have an autoincrement column.

Here in the below case id is an identity column

select t1.Field1 , SUM(t2.Field1) as field2
from @t t1
inner join @t t2 on t1.id >= t2.id
group by t1.id, t1.Field1
order by t1.id

P.Siva
Go to Top of Page

ShivaKrishna
Starting Member

20 Posts

Posted - 2013-08-28 : 05:53:52
select t1.Field1 , SUM(t2.Field1) as Field2
from @t t1
inner join @t t2 on t1.id >= t2.id
group by t1.Field1
Go to Top of Page
   

- Advertisement -