如何根据单个表中的共享ID更新行

时间:2017-09-18 14:22:02

标签: sql sql-server

目前我的表格如下所示:

ID|Date    |Val1|Val2|        
1 |1/1/2016|1000|0         
2 |1/1/2016|Null|0  
3 |1/1/2016|Null|0  
1 |2/1/2016|1000|0  
2 |2/1/2016|Null|0  
3 |2/1/2016|1000|0 
1 |3/1/2016|1000|0   
2 |3/1/2016|1000|0   
3 |3/1/2016|1000|0

如果val2填充1,我希望Val1成为month,因此输出如下:

ID|Date    |Val1|Val2|        
1 |1/1/2016|1000|0         
2 |1/1/2016|Null|0  
3 |1/1/2016|Null|0      
1 |2/1/2016|1000|1   
2 |2/1/2016|Null|0  
3 |2/1/2016|1000|0     
1 |3/1/2016|1000|1  
2 |3/1/2016|1000|0   
3 |3/1/2016|1000|1

我尝试了一些代码组合,但是在Val1首次出现的前一个日期更新值的条件是让我失望。我很感激任何帮助!

1 个答案:

答案 0 :(得分:0)

您可以使用窗口LAG()来查找之前的值,并更新Val2 NOT NULL

;With Cte As
(
    Select  Id, [Date-----], Val1, Val2,
            Lag(Val1) Over (Partition By Id Order By [Date-----] Asc) As Prev
    From    LikeBelow
)
Update  Cte
Set     Val2 = 1 
Where   Prev Is Not Null;

如果您实际将日期存储为VARCHAR而不是DATE,则需要将其转换为:

;With Cte As
(
    Select  Id, [Date-----], Val1, Val2,
            Lag(Val1) Over (Partition By Id 
                            Order By Convert(Date, [Date-----]) Asc) As Prev
    From    LikeBelow
)
Update  Cte
Set     Val2 = 1 
Where   Prev Is Not Null;