这是关于Get age from thebirthday field with type date using SQL的后续问题。我date
在 MySQL 数据库中有一个字段用于用户的生日,并使用以下查询获取年龄:
SELECT
ROUND(DATEDIFF(
Cast((SELECT NOW()) as Date),
Cast(birthday as Date)
) / 365, 0) as age
FROM member
现在,我需要选择不同年龄段的人数。例如,我需要知道 13-17、18-21、22-25、26-35、36-50、51-MAX 年龄组中有多少人。
这可能使用MySQL吗?
我想过UNION
s,像这样:
SELECT
ROUND(DATEDIFF(
Cast((SELECT NOW()) as Date),
Cast(birthday as Date)
) / 365, 0) as age,
1 as agegroup
FROM member WHERE age >=13 AND age <=17
UNION
SELECT
ROUND(DATEDIFF(
Cast((SELECT NOW()) as Date),
Cast(birthday as Date)
) / 365, 0) as age
2 as agegroup
FROM member WHERE age >=18 AND age <=21
但这将是漫长而丑陋的。肯定有更好的办法!