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

相关推荐
Java后端的Ai之路1 小时前
Text-to-SQL与智能问数完全指南:基本概念、核心原理、Python实战教学及企业项目落地
数据库·python·sql·text-to-sql·智能问数
Elastic 中国社区官方博客1 小时前
Prometheus Remote Write 在 Elasticsearch 中的摄取原理
大数据·数据库·elasticsearch·搜索引擎·信息可视化·全文检索·prometheus
2601_949816681 小时前
Spring boot启动原理及相关组件
数据库·spring boot·后端
2301_782659181 小时前
如何使用Navicat连接云端MariaDB_白名单与实例配置
jvm·数据库·python
2301_803875618 小时前
PHP 中处理会话数组时的类型错误解析与修复指南
jvm·数据库·python
m0_743623928 小时前
c++如何批量修改文件后缀名_std--filesystem--replace_extension【实战】
jvm·数据库·python
2501_914245938 小时前
CSS如何处理CSS变量作用域冲突_利用特定类名重写变量值
jvm·数据库·python
maqr_11010 小时前
MySQL数据库迁移到云端如何保障安全_数据加密与SSL连接配置
jvm·数据库·python
u01091476010 小时前
MySQL如何限制触发器递归调用的深度_防止触发器死循环方法
jvm·数据库·python
weixin_3812881810 小时前
MySQL中如何使用HEX函数转换十六进制_MySQL进制转换函数
jvm·数据库·python