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