sql -- update表子查詢、多條件判斷case when


表結構:

需求

思路:

  1. 求出平均數
    select avg(user_total) as avg from user_level
  2. 更新他的等級
    update user_level set user_rank= xxx  where user_total >= 平均數

when case 表達式:

case 
  when 表達式 then表達式 

  else 表達式

 end 
select *,
       case user_total
           when 100 then '消費正好滿100的用戶'
           else '其他'
           end
from user_level;
select *,
       case
           when user_total > 50 and user_total < 100 then '消費超過50的用戶'
           when user_total > 100 then '消費超過100的用戶'
           else '其他'
           end
from user_level;

update里邊也可以使用when case

最終答案:

update user_level,(select avg(user_total) as avg from user_level) b
set user_rank=
        case
            when round(user_total / avg) >= 1 and round(user_total / avg) < 2 then '白金用戶'
            when round(user_total / avg) >= 2 then '黃金用戶'

            ELSE
                '吃瓜'
            end
where user_total >= b.avg;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM