表stu数据如下
根据出生日期查询年龄
SELECT TIMESTAMPDIFF(YEAR,DATE(birthdate),CURDATE()) AS age FROM stu;
返回结果:
函数DATE():提取日期或日期/时间表达式的日期部分;
函数CURDATE():返回当前的日期;
函数TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2):计算两个日期的时间差,unit是计算时间差的单位,可以是SECOND秒、MINUTE分钟、HOUR小时、DAY天、WEEK星期、MONTH月、QUARTER季度、YEAR年。
对年龄进行分组统计
1)case 结构
SELECT年龄段,count(*) 人数FROM(SELECTCASEWHEN TIMESTAMPDIFF(YEAR,DATE(birthdate),CURDATE())<20 THEN'20岁以下' WHEN TIMESTAMPDIFF(YEAR,DATE(birthdate),CURDATE()) >= 20 AND TIMESTAMPDIFF(YEAR,DATE(birthdate),CURDATE()) <= 22 THEN'20-22岁' WHEN TIMESTAMPDIFF(YEAR,DATE(birthdate),CURDATE()) >= 23 AND TIMESTAMPDIFF(YEAR,DATE(birthdate),CURDATE()) <= 25 THEN'23-25岁' WHEN TIMESTAMPDIFF(YEAR,DATE(birthdate),CURDATE())>25 THEN '25岁以上' else '未知'END AS 年龄段FROM stu) AS a GROUP BY 年龄段;
2)if结构
SELECT 年龄段,count(*) 人数FROM(SELECTIF(TIMESTAMPDIFF(YEAR,DATE(birthdate),CURDATE())<20,'20岁以下',IF(TIMESTAMPDIFF(YEAR,DATE(birthdate),CURDATE())>= 20 AND TIMESTAMPDIFF(YEAR,DATE(birthdate),CURDATE()) <= 22,'20-22岁',IF(TIMESTAMPDIFF(YEAR,DATE(birthdate),CURDATE())>= 23 AND TIMESTAMPDIFF(YEAR,DATE(birthdate),CURDATE()) <= 25,'23-25岁',IF(TIMESTAMPDIFF(YEAR,DATE(birthdate),CURDATE())>25,'25岁以上','未知'))))AS 年龄段FROM stu)AS aGROUP BY 年龄段;
返回结果:
来源地址:https://blog.csdn.net/yuyan98/article/details/128846732