使用SQL选择年龄组

时间:2013-06-17 11:41:49

标签: mysql sql database

这是关于Get age from the birthday field with type date using SQL的后续问题。我在MySQL数据库中有一个date字段用于用户的生日,并使用此查询获取年龄:

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

但那将是漫长而丑陋的。必须有更好的方法!

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

如果需要,可能更容易扩展,或者转移到使用表中的日期范围(因此,如果需要,用户可以轻松更新结果报告)。

答案 2 :(得分: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

可能会有轻微的变化,因为年龄不在其自己的列中,或者您想要额外或不同的范围。我相信你可以自己解决这个问题!