1

这是关于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吗?

我想过UNIONs,像这样:

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

但这将是漫长而丑陋的。肯定有更好的办法!

4

3 回答 3

3
select  AgeGroup
,       count(*)
from    (
        select  case
                when  age between 13 and 17 then 1
                when  age between 18 and 21 then 2
                ...
                end as AgeGroup
        from    (
                SELECT  ROUND(DATEDIFF(Cast(NOW() as Date),
                            Cast(birthday as Date)) / 365, 0) as age
                FROM    YourTable
                ) as SubQueryAlias
        ) as SubQueryAlias2
group by
        AgeGroup
于 2013-06-17T11:45:11.043 回答
2

另一种可能的解决方案: -

SELECT  AgeRange.MinAge, AgeRange.MaxAge, COUNT(*)
FROM    
(
    SELECT 13 AS MinAge, 17 AS MaxAge
    UNION SELECT 18, 21
    UNION SELECT 22, 25
    UNION SELECT 26, 35
    UNION SELECT 36, 50
    UNION SELECT 51, 9999
) AgeRange
INNER JOIN YourTable
ON ROUND(DATEDIFF(CAST(NOW() as DATE), CAST(birthday as DATE)) / 365, 0) BETWEEN AgeRange.MinAge AND AgeRange.MaxAge 
GROUP BY AgeRange.MinAge, AgeRange.MaxAge

如果需要,可能更容易扩展,或者使用表格中的日期范围(因此用户可以在需要时轻松更新生成的报告)。

于 2013-06-17T13:04:34.997 回答
0

如果您将年龄作为表格中的一列,您会这样做:

SELECT
    SUM(CASE WHEN age < 10 THEN 1 ELSE 0 END) AS under10,
    SUM(CASE WHEN 10<age AND age <19 THEN 1 ELSE 0 END) AS age10to19,
    .
    .
    .
FROM table

可能会有微小的变化,因为年龄不在其自己的列中,或者如果您想要额外或不同的范围。我相信你可以自己解决它们!

于 2013-06-17T11:46:07.803 回答