Mysql出生日期转换为年龄并分组统计人数的方法示例

2022-07-28,,,,

查询数据库

select * from `student`

查询结果

id name birthday
1 张三 1970-10-01
2 李四 1990-10-01
3 王五 2002-10-01
4 马六 2003-10-01

转换为年龄的查询语句,使用函数timestampdiff

select id, name, birthday, timestampdiff(year,student.birthday,curdate()) as age from `student`

查询结果

d name birthady age
1 张三 1970-10-01 50
2 李四 1990-10-01 30
3 王五 2002-10-01 18
4 马六 2003-10-01 17

然后按照年龄段进行分组

select
	group_concat(a.id) as ids,
	group_concat(a.name) as names,
	case
		when a.age<18 then '少年'
		when a.age>=18 and a.age< 40 then '青年'
		when a.age>=40 and a.age< 60 then '中年'
	end as age,
	count(a.id) as count
from
	(select id, name, birthday, timestampdiff(year,student.birthday,curdate()) as age from `student`) as a
group by
	case
		when a.age<18 then '少年'
		when a.age>=18 and a.age< 40 then '青年'
		when a.age>=40 and a.age< 60 then '中年'
	end

查询结果

ids names age count
1 张三 中年 1
4 马六 少年 1
2,3 李四,王五 青年 2

tips:当前时间是2020年

总结

到此这篇关于mysql出生日期转换为年龄并分组统计人数的文章就介绍到这了,更多相关mysql出生日期转年龄并分组统计内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Mysql出生日期转换为年龄并分组统计人数的方法示例.doc》

下载本文的Word格式文档,以方便收藏与打印。