繁体   English   中英

SQL用条件更新多行

[英]SQL update multiple rows with condition

Name   id  Col1  Col2  Col3 
Row1   1    6     1     A    
Row2   2    2     3     B    
Row3   3    9     5     B    
Row4   4    16    8     C    

我想更新条件列。

在第一行,

update col2 = Col1+0 if Col3 = A 
OR 
col2 = Col1-0 if Col3 = B 
OR 
col2 = Col1*0 if Col3 = C

在第二行中

update col2 = (previous col2) + Col1 if Col3 = A 
OR
col2 = (previous col2) - Col1 if Col3 = B 
OR
col2 = (previous col2) * Col1 if Col3 = C 

第三行也一样

我认为您可以使用case语句和变量来完成所需的操作:

set @prev_col2 = 0;

update t
    set col2 = (case when (@col2 := @prev_col2) = NULL then -1 -- never happens
                     when (@prev_col2 := col2) = NULL then -1  -- never happens
                     when col3 = 'A' then Col1 + @col2
                     when col3 = 'B' then Col1 - @col2
                     when Col3 = 'C' then col1 * @col2
                end)
    order by id;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM