sql -- update表子查询、多条件判断case when

表结构:spa

需求code

思路:blog

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

when case 表达式:class

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 casedate

最终答案:select

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;
相关文章
相关标签/搜索