2

I have a table with some columns and I want to update current row data with previous adding current row another column value to it. Below is my table

   Date     Type      Temp   Value
2018-04-24  TypeA       0     5
2018-04-25  TypeA       0     12
2018-04-26  TypeA       0     21
2018-04-27  TypeA       0     14
2018-04-30  TypeA       0     16
2018-05-01  TypeA       0.6   18
2018-04-25  TypeB       0     20
2018-04-26  TypeB       0     81
2018-04-27  TypeB       1     42
2018-04-30  TypeB       0     65
2018-05-01  TypeB       0.6   22

I want output to be such that - value column = previous row value column + current row temp.

   Date     Type      Temp   Value
2018-04-24  TypeA       0     5
2018-04-25  TypeA       0     5
2018-04-26  TypeA       0     5
2018-04-27  TypeA       0     5
2018-04-30  TypeA       0     5
2018-05-01  TypeA       0.6   5.6
2018-04-25  TypeB       0     20
2018-04-26  TypeB       0     20
2018-04-27  TypeB       1     21
2018-04-30  TypeB       0     21
2018-05-01  TypeB       0.6   21.6

I have tried to write a query but I am only able to update previous row into current row.

The query I have used is:

UPDATE testTable
SET Value = (select ISNULL(lag(m2.Value,1) over(partition by Type order by Date),testTable.Value) as lag1
                    from testTable m2
                    where m2.Date= testTable.Date
                    and
                    m2.Type= testTable.Type
                   )
Deep Sharma
  • 3,374
  • 3
  • 29
  • 49

1 Answers1

3

Here is one approach using a First_Value() and Sum() over()

Example

Declare @YourTable Table ([Date] date,[Type] varchar(50),[Temp] decimal(10,2),[Value] decimal(10,2))
Insert Into @YourTable Values 
 ('2018-04-24','TypeA',0,5)
,('2018-04-25','TypeA',0,12)
,('2018-04-26','TypeA',0,21)
,('2018-04-27','TypeA',0,14)
,('2018-04-30','TypeA',0,16)
,('2018-05-01','TypeA',0.6,18)
,('2018-04-25','TypeB',0,20)
,('2018-04-26','TypeB',0,81)
,('2018-04-27','TypeB',1,42)
,('2018-04-30','TypeB',0,65)
,('2018-05-01','TypeB',0.6,22)

;with cte0 as (
      Select  *
             ,NewValue = FIRST_VALUE(Value) over (Partition By [Type] Order By [Date]) 
                        +Sum(Temp) over (Partition By [Type] Order By [Date]) 
        From  @YourTable
)
Update cte0 set Value = NewValue

The Updated Table

enter image description here

John Cappelletti
  • 79,615
  • 7
  • 44
  • 66