mysql统计各个年龄段有多少人数

通过生日字段来计算年龄

select distinct u.user_id,TIMESTAMPDIFF(YEAR,u.birthday,CURDATE()) AS 'age'
        from sys_user u

将计算出来的年龄进行分组

这里我用1代表小于20,2代表20-30,3代表30-40以此类推,
后面的union 表示如果该年龄段没有人,则默认为0

select 
	count(1) `value`,
	if(u.age<=20,'1',
		if(20<u.age and u.age<=30,'2',
			if(30<u.age and u.age<=40,'3',
				if(40<u.age and u.age<=50,'4',
					if(50<u.age and u.age<=60,'5',
						if(60<u.age,'6','0')
					)
				)
			)
		)
	) `type`
	from 
	(
	select distinct u.user_id,TIMESTAMPDIFF(YEAR,u.birthday,CURDATE()) AS 'age'
			from sys_user u
	) u
	GROUP BY `type`
	UNION (SELECT 0,'0')
	UNION (SELECT 0,'1')
	UNION (SELECT 0,'2')
	UNION (SELECT 0,'3')
	UNION (SELECT 0,'4')
	UNION (SELECT 0,'5')
	UNION (SELECT 0,'6')

最后将年龄段进行处理

select `value`,
CASE `type` 
WHEN '1' THEN '小于20' 
WHEN '2' THEN '21-30' 
WHEN '3' THEN '31-40' 
WHEN '4' THEN '41-50' 
WHEN '5' THEN '51-60' 
WHEN '6' THEN '大于60' 
ELSE '无'
END `name`
from 
(
	select 
	count(1) `value`,
	if(u.age<=20,'1',
		if(20<u.age and u.age<=30,'2',
			if(30<u.age and u.age<=40,'3',
				if(40<u.age and u.age<=50,'4',
					if(50<u.age and u.age<=60,'5',
						if(60<u.age,'6','0')
					)
				)
			)
		)
	) `type`
	from 
	(
	select distinct u.user_id,TIMESTAMPDIFF(YEAR,u.birthday,CURDATE()) AS 'age'
			from sys_user u
	) u
	GROUP BY `type`
	UNION (SELECT 0,'0')
	UNION (SELECT 0,'1')
	UNION (SELECT 0,'2')
	UNION (SELECT 0,'3')
	UNION (SELECT 0,'4')
	UNION (SELECT 0,'5')
	UNION (SELECT 0,'6')
) a
GROUP BY `name`
ORDER BY `type`

ps:如果放在mybatis中,注意下<和>,采用"&lt;“或”&gt;"
有不对的地方,还望大神指点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值