牛客网-牛客题霸-sql入门篇-SQL26题解
描述
题目:现在运营想要将用户划分为25岁以下和25岁及以上两个年龄段,分别查看这两个年龄段用户数量
本题注意:age为null 也记为 25岁以下
示例:user_profile
根据示例,你的查询应返回以下结果:
解法一:
使用union联合查询 ,分别查询出25岁以下和25岁及以上的数据(注意age为空时,算作25岁以下)使用count计数
代码如下
select '25岁以下' age_cut,count(device_id) number
from user_profile
where age<25 or age is null
union
select '25岁及以上',count(device_id)
from user_profile
where age>=25
解法二:
使用if函数,判断是age小于25和age是否为空,然后使用group by 分组count分别计数
代码如下
select if(age<25 or age is null,'25岁以下','25岁及以上') age_cut,
count(device_id) number
from user_profile
group by age_cut
解法三:
使用case,when之后写判断语句age小于25和age是否为空,使用then,else
然后使用group by 分组count分别计数
代码如下
select
(case
when age<25 or age is null
then '25岁以下'
else '25岁及以上'
end
) age_cut,count(device_id) number
from user_profile
group by age_cut