【场景】:查看每个类别的情况

【分类】:条件函数、union

分析思路

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

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

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

最终结果

select 查询结果 [年龄类别;人数]
from 从哪张表中查询数据[用户表]
group by 分组条件 [年龄类别]

扩展

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

求解代码

方法一:

条件函数:if()

select
    if(age >= 25, '25岁及以上', '25岁以下') as age_cut,
    count(device_id) AS number
from user_profile
group by age_cut

方法二

条件函数:case when

select
    (
    case 
        WHEN age >= 25 then '25岁及以上' 
        else '25岁以下'
    end
    ) as age_cut,
    count(device_id) as number
from user_profile
group by age_cut

方法三

union

(
#统计25岁以下学生的人数
select
    '25岁以下' as age_cut,
    COUNT(device_id) as number
from user_profile
where age < 25 or age is null
)
union
(
#统计25岁以上学生的人数
select
    '25岁及以上' as age_cut,
    COUNT(device_id) as number
from user_profile
where age >= 25
)