簡體   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