我有一个DoB字段。我想根据年龄将所有用户分类/分组到这些组中:
答案 0 :(得分:1)
有几种方法可以做到这一点。如果您没有很多记录,可以执行类似
的操作select floor((datediff(now(),DOB_at)/365)/5) as year_group, count(*)
from users
group by floor((datediff(now(),DOB)/365)/5)
必须对此进行调整,以对20岁以下或50岁以上的DOB进行分组。
稍微好一点的方法是在您的组中设置一个查找表,它有两列,year_diff和group_name。
year_diff group_name
....values.....
18 '<20'
19 '<20'
20 '20-25'
21 '20-25'
22 '20-25'
23 '20-25'
24 '20-25'
25 '20-25'
26 '26-30'
....values.....
您的查询将是
select dob_lookup.group_name, count(*)
from users
join dob_lookup on floor((datediff(now(),users.DOB)/365)/5) = dob_lookup.year_diff
group by dob_lookup.group_name
答案 1 :(得分:1)
SELECT
CASE
WHEN age < 20 THEN 'Under 20'
WHEN age BETWEEN 20 and 29 THEN '20 - 29'
WHEN age BETWEEN 30 and 39 THEN '30 - 39'
WHEN age BETWEEN 40 and 49 THEN '40 - 49'
WHEN age BETWEEN 50 and 59 THEN '50 - 59'
WHEN age BETWEEN 60 and 69 THEN '60 - 69'
WHEN age BETWEEN 70 and 79 THEN '70 - 79'
WHEN age >= 80 THEN 'Over 80'
WHEN age IS NULL THEN 'Not Filled In (NULL)'
END as age_range,
COUNT(*) AS count
FROM (SELECT TIMESTAMPDIFF(YEAR, dob, CURDATE()) AS age FROM gamers) as derived
GROUP BY age_range
ORDER BY age_range
答案 2 :(得分:0)
唯一想到的是在表格中追加一个字段(比如'age_group')并在插入时填充它。然后,您可以使用group by age_group
轻松对其进行分组。