MySQL 根据出生日期根据年龄区间进行统计汇总

年龄采取四舍五入的方式,如出生日期2018-08-02,如果今天是2018-09-01差一天满,将处理为1岁显示
如果不需要四舍五入则使用: TIMESTAMPDIFF(YEAR, @birthday, CURDATE())

SELECT t.age_range,COUNT(1) FROM (SELECT  CASE 
    WHEN  ROUND(DATEDIFF(CURDATE(), birthday)/365.2422)> 0 AND ROUND(DATEDIFF(CURDATE(), birthday)/365.2422)<  20  THEN '20岁以下' 
    WHEN  ROUND(DATEDIFF(CURDATE(), birthday)/365.2422)>=20 AND ROUND(DATEDIFF(CURDATE(), birthday)/365.2422)<  30  THEN '20-30岁' 
    WHEN  ROUND(DATEDIFF(CURDATE(), birthday)/365.2422)>=30 AND ROUND(DATEDIFF(CURDATE(), birthday)/365.2422)<  40  THEN '30-40岁' 
    WHEN  ROUND(DATEDIFF(CURDATE(), birthday)/365.2422)>=40 AND ROUND(DATEDIFF(CURDATE(), birthday)/365.2422)<  50  THEN '40-50岁' 
    WHEN  ROUND(DATEDIFF(CURDATE(), birthday)/365.2422)>=50 AND ROUND(DATEDIFF(CURDATE(), birthday)/365.2422)<  60  THEN '50-60岁' 
    WHEN  ROUND(DATEDIFF(CURDATE(), birthday)/365.2422)>=60 AND ROUND(DATEDIFF(CURDATE(), birthday)/365.2422)<  70  THEN '60-70岁' 
    WHEN  ROUND(DATEDIFF(CURDATE(), birthday)/365.2422)>=70 THEN '70以上' 
    ELSE '未知' END as age_range FROM account_info) as t GROUP BY t.age_range;

你可能感兴趣的:(MySQL 根据出生日期根据年龄区间进行统计汇总)