使用上一行SQL Server更新当前行

时间:2018-10-15 13:20:28

标签: sql sql-server tsql sql-server-2014

我有一个包含一些列的表,我想用先前添加当前行的另一个列值来更新当前行的数据。下面是我的桌子

   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

我希望输出为-值列=上一行值列+当前行温度。

   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

我尝试编写查询,但是我只能将前一行更新为当前行。

我使用的查询是:

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
                   )

1 个答案:

答案 0 :(得分:3)

这是使用First_Value()Sum() over()

的一种方法

示例

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

更新后的表格

enter image description here