“21天好习惯”第一期——6

牛客网-牛客题霸-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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值