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之后计数的。

相关推荐
JSON_L1 小时前
Fastadmin中实现敏感词管理
数据库·php·fastadmin
不是起点的终点2 小时前
【实战】Python 一键生成数据库说明文档(对接阿里云百炼 AI,输出 Word 格式)
数据库·python·阿里云
2301_813599554 小时前
Go语言怎么做秒杀系统_Go语言秒杀系统实战教程【实用】
jvm·数据库·python
NCIN EXPE8 小时前
redis 使用
数据库·redis·缓存
MongoDB 数据平台8 小时前
为编码代理引入 MongoDB 代理技能和插件
数据库·mongodb
极客on之路8 小时前
mysql explain type 各个字段解释
数据库·mysql
代码雕刻家9 小时前
MySQL与SQL Server的基本指令
数据库·mysql·sqlserver
lThE ANDE9 小时前
开启mysql的binlog日志
数据库·mysql
yejqvow129 小时前
CSS如何控制placeholder文字的颜色_使用--placeholder伪元素
jvm·数据库·python
oLLI PILO9 小时前
nacos2.3.0 接入pgsql或其他数据库
数据库