**题解 | #计算25岁以上和以下的用户数量#caseif

计算25岁以上和以下的用户数量

https://www.nowcoder.com/practice/30f9f470390a4a8a8dd3b8e1f8c7a9fa

# 法1 case函数的使用
# CASE 测试表达式
# WHEN 简单表达式1 THEN 结果表达式1
# WHEN 简单表达式2 THEN 结果表达式2 …
# WHEN 简单表达式n THEN 结果表达式n
# [ ELSE 结果表达式n+1 ]
# END AS 字段别名

select 
    case 
        when age >=25 then '25岁及以上'
        when age <25 or age is null then '25岁以下'
        end as age_cut,
    count(device_id) as number
from user_profile
group by age_cut;
/*
SQL执行顺序中select明明在groupby后面,但是这里为什么能用别名age_cut。

原因:因为MySQL对查询做了增强没有严格遵循SQL的执行顺序,where后面不能用select中的别名,但是group by 是可以的,Oracle数据库严格遵循了SQL执行顺序在Oracle里group by是不能引用select里的别名的。Mysql执行顺序应该是 from,where,select,group by,having,order by,limit*/

# /法2:IF函数
select 
if(age>=25,'25岁及以上','25岁以下') as age_cut,
count(device_id) as number
from user_profile
group by age_cut;


# 法3 union all
select '25岁以下' as age_cut,count(device_id) as number
from user_profile
where age<25 or age is null
union all
select '25岁及以上' as age_cut,count(device_id) as number
from user_profile
where age>=25 ;



SQL错题 文章被收录于专栏

每天学习一遍 刷题刷题 越刷越强!

全部评论

相关推荐

lllllkin:感觉可以精简到一页简历,有些排版感觉不是必须的。 时间线越早的,你自己越熟悉的放前面。描述可以更精简些,一些问题解决感觉可以不用写具体技术栈,卖个关子,等面试官问。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务