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;
原文地址:https://www.cnblogs.com/8013-cmf/p/11171751.html