根据年龄分割查询每个年龄段的人数

本文介绍了如何使用SQL进行分段查询,以统计不同年龄段的人数。分别通过常规的WHEN CASE语句和ELT(INTERVAL())函数两种方法实现,其中ELT方法利用了MySQL的特定函数,详细解释可在官方文档中查阅。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

根据年龄分割查询每个年龄段的人数

本文以两种查询方式,查询每个年龄段的人数。

1.普通的when case 查询

select age, count(*) as num from (
SELECT 
case 
when age >= 18 and age <= 20 then '1'
when age >= 21 and age <= 25 then '2'
when age >= 26 and age <= 30 then '3'
when age >= 31 and age <= 35 then '4'
when age >= 36 and age <= 40 then '5'
when age is NULL or age < 18 then '0'
WHEN age > 40 then '6'
end 
as age from t_yuefu_v4_user WHERE recordStatus >= 0) a
WHERE 1=1
group by age

查询的意思也跟SQL一样,简单易懂。

2.ELT(INTERVAL())查询方式查询

select ifnull(elt(INTERVAL(age, 18,21,26,31,36,40)+1, '<18','18~20','21~25','26~30','31~35','36~40','>=40'),'未输入') as ageRange,
count(INTERVAL(age, 18,21,25,30,35,40)) as count 
from t_yuefu_v4_user  
where recordStatus >= 0 group by ageRange;

这种查询方式利用到两个函数,函数的详细解释在Mysql的官方文档可以看到。

ELT方法的官方解释如下:—— [ ELT Function ]

 ELT(N,str1,str2,str3,...)

ELT() returns the Nth element of the list of strings: str1 if N = 1, str2 if N = 2, and so on. Returns NULL if N is less than 1 or greater than the number of arguments. ELT() is the complement of FIELD().

mysql> SELECT ELT(1, 'ej', 'Heja', 'hej', 'foo');
        -> 'ej'
mysql> SELECT ELT(4, 'ej', 'Heja', 'hej', 'foo');
        -> 'foo'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值