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

描述

题目:现在运营想要将用户划分为25岁以下和25岁及以上两个年龄段,分别查看这两个年龄段用户数量

本题注意:age为null 也记为 25岁以下

示例:user_profile

|----|-----------|--------|-----|------------|-----|-----------------------|--------------|------------|
| id | device_id | gender | age | university | gpa | active_days_within_30 | question_cnt | answer_cnt |
| 1 | 2138 | male | 21 | 北京大学 | 3.4 | 7 | 2 | 12 |
| 2 | 3214 | male | | 复旦大学 | 4 | 15 | 5 | 25 |
| 3 | 6543 | female | 20 | 北京大学 | 3.2 | 12 | 3 | 30 |
| 4 | 2315 | female | 23 | 浙江大学 | 3.6 | 5 | 1 | 2 |
| 5 | 5432 | male | 25 | 山东大学 | 3.8 | 20 | 15 | 70 |
| 6 | 2131 | male | 28 | 山东大学 | 3.3 | 15 | 7 | 13 |
| 7 | 4321 | male | 26 | 复旦大学 | 3.6 | 9 | 6 | 52 |

根据示例,你的查询应返回以下结果:

|---------|--------|
| age_cut | number |
| 25岁以下 | 4 |
| 25岁及以上 | 3 |

题解

(1)用if函数的写法。

|-------|-------------------------------------------------------------------------------------------------------------------------|
| 1 2 3 | SELECT IF(age>=``25``,``"25岁及以上"``,``"25岁以下"``) AS age_cut,count(*) AS number FROM user_profile GROUP BY age_cut; |

(2)case的写法。

|---------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 1 2 3 4 5 6 7 | select ``(``case ``when age>=``25 then ``'25岁及以上' ``else '25岁以下' end) as age_cut, ``count(*) as number from user_profile group by age_cut |

两个as,还有记得count是GROUP BY之后计数的。

相关推荐
高梦轩1 小时前
MySQL高可用
android·运维·数据库
紫金修道4 小时前
【DeepAgent】概述
开发语言·数据库·python
孟章豪4 小时前
《SQL拼接 vs 参数化,为什么公司禁止拼接SQL?(附真实案例)》
服务器·数据库·sql
荒川之神4 小时前
ORACLE LEVEL函数练习
数据库·oracle
·云扬·5 小时前
【MySQL】实战:用pt-table-sync修复主从数据一致性问题
数据库·mysql·ffmpeg
swIn KWAL5 小时前
【MySQL】环境变量配置
数据库·mysql·adb
shark22222225 小时前
【JOIN】关键字在MySql中的详细使用
数据库·mysql
RATi GORI5 小时前
MySQL中的CASE WHEN语句:用法、示例与解析
android·数据库·mysql
坊钰5 小时前
Java 死锁问题及其解决方案
java·开发语言·数据库
onebound_noah6 小时前
【实战教程】如何通过API快速获取淘宝/天猫商品评论数据(含多语言Demo)
大数据·数据库