tad stones
tad stones

Reputation: 57

SQL - Add value with previous row only

I have a table named myvals with the following fields:

ID   number
--   -------
1     7
2     3
3     4
4     0
5     9

Starting on 2nd row, I would like to add the number with the previous row number. So, my end result would look like this

ID   number
--   ------
1      7
2     10
3      7
4      4
5      9

Upvotes: 2

Views: 2118

Answers (3)

Anup Nayak
Anup Nayak

Reputation: 1

create table #temp
(
    month_type datetime,
    value int


)
insert into #temp
Select '2015/01/01',1
union
Select '2015/02/01',2
union
Select '2015/03/01',3
union
Select '2015/04/01',4



SELECT t.value,t1.value,(t.value+t1.value)/2 FROM #temp t1
left join #temp t on t.month_type=Dateadd(MONTH,-1,t1.month_type)

Upvotes: -1

Michael Mairegger
Michael Mairegger

Reputation: 7301

You could use the LAG analytic function

SELECT Id, number + LAG(number,1,0) OVER (ORDER BY Id) FROM table

Upvotes: 6

ArtK
ArtK

Reputation: 1185

First thing's first. You can't add to null to ID 1 must have a value.

Upvotes: 0

Related Questions