【场景】:多个条件

【分类】:条件函数、if嵌套

分析思路

难点:

1.如何根据条件输出内容

一个条件2个结果可以使用if、case when;多个条件多个结果可以使用case when,还有if嵌套

(1)分别查看这两个年龄段用户数量

[使用]:if()或者case when;group by

扩展

前往查看:MySQL 条件函数 case when、if、ifnull

求解代码

方法一:

条件函数:if()

select
    device_id,
    gender, 
    if(age <20, '20岁以下',
        if(age >=25, '25岁及以上', 
            if(age between 20 and 24, '20-24岁', '其他'))) as age_cut
from user_profile

方法二

条件函数:case when

select
    device_id,
    gender,
    (case
        when age < 20  then '20岁以下'
        when age >= 20 and age <= 24 then '20-24岁'
        when age >= 25 then '25岁及以上'
        else '其他'
    end) as age_cut
from user_profile