按年龄范围分组在MySQL中

时间:2016-07-21 11:41:57

标签: mysql sql

我们在表格中有一个出生日期(类型日期)和user_id,我们希望根据出生日期字段按年龄计算用户组数

例如运行后,我们得到以下记录

Age  Total_Users 
1-20    50
20-30   100
30-50   500
50-100  600

我们如何编写这种类型的查询?请建议。目前我是 通过PHP代码管理,但由于大量的记录,它需要花费太多时间 谢谢

1 个答案:

答案 0 :(得分:1)

可能是下面的查询就可以完成这项工作。

SELECT 
CASE WHEN (DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(birth_date, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(birth_date, '00-%m-%d'))) <= 20 THEN '1-20'
     WHEN (DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(birth_date, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(birth_date, '00-%m-%d'))) <= 30 THEN '20-30'
     WHEN (DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(birth_date, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(birth_date, '00-%m-%d'))) <= 50 THEN '30-50'
     WHEN (DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(birth_date, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(birth_date, '00-%m-%d'))) <= 50 THEN '50-100' END AS age,
COUNT(*) total
FROM dob_table
GROUP BY age;

WORKING DEMO

<强>输入:

| id |                 birth_date |
|----|----------------------------|
|  1 | February, 01 2014 00:00:00 |
|  2 | February, 01 2014 00:00:00 |
|  3 | February, 01 2014 00:00:00 |
|  4 | February, 01 2010 00:00:00 |
|  5 | February, 27 1989 00:00:00 |
|  6 | February, 27 1989 00:00:00 |
|  7 | February, 27 1989 00:00:00 |
|  8 | February, 27 1989 00:00:00 |
|  9 | February, 27 1989 00:00:00 |

<强>输出:

age      total
1-20        4
20-30       5