[英]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
I want to update the column with condition. 我想更新条件列。
In first row, 在第一行,
update col2 = Col1+0 if Col3 = A
OR
col2 = Col1-0 if Col3 = B
OR
col2 = Col1*0 if Col3 = C
In second row, 在第二行中
update col2 = (previous col2) + Col1 if Col3 = A
OR
col2 = (previous col2) - Col1 if Col3 = B
OR
col2 = (previous col2) * Col1 if Col3 = C
The same goes to third row 第三行也一样
I think you can do what you want with a case statement and variables: 我认为您可以使用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.