SELECT grade, IFNULL(COUNT(1), 0) FROM (SELECT CASE WHEN old >= 0 AND old < 20 THEN '0' WHEN old >= 20 AND old < 30 THEN '1' WHEN old >= 30 AND old < 45 THEN '2' WHEN old >= 45 THEN '3' END AS grade FROM (SELECT year(curdate()) - if(length(idCard) = 18, substring(idCard, 7, 4), if(length(idcard) = 15, concat('19', substring(idCard, 7, 2)), NULL)) AS old FROM `user` WHERE idCard IS NOT NULL AND idCard != '') a) b GROUP BY grade order by grade;