根据出生日期将MySQL结果分组到年龄组

时间:2017-04-25 09:02:07

标签: php mysql

我有一个MySQL表persons,有3列,idname& date_of_birth。 我的表有大约100行数据,但这可能会增加。

我想使用PHP根据年龄组输出人员,所以:

20-25: 10
26-35: 15
36-45: 12
46-55: 20
55+: 30

现在,我只是使用PHP来使用这段代码获取所有出生日期:

$sql2 = "SELECT date_of_birth FROM persons";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
    $date_of_birth = explode('-', $row2['date_of_birth']);
    $year = $date_of_birth[0];
    $month = $date_of_birth[1];
    $day = $date_of_birth[2];
    echo 'Year of Birth: '.$year.'<br>';
}

有人可以指导我按正确的方向处理按年龄组分组我的结果吗?

我确实在另一个SO帖子中找到了这个,但不确定它是否在上述环境中有用:SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age

3 个答案:

答案 0 :(得分:5)

我会通过在MySQL查询本身中分配年龄组来处理这个问题,然后让PHP显示结果集。您可以尝试以下查询:

SELECT t.age_group, COUNT(*) AS age_count
FROM
(
    SELECT
        CASE WHEN TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) BETWEEN 20 AND 25
             THEN '20-25'
             WHEN TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) BETWEEN 26 AND 35
             THEN '26-35'
             WHEN TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) BETWEEN 36 AND 45
             THEN '36-45'
             WHEN TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) BETWEEN 46 AND 55
             THEN '46-55'
             WHEN TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) > 55
             THEN '46-55'
             ELSE 'Other'
        END AS age_group
    FROM persons
) t
GROUP BY t.age_group

内部查询为每条记录分配一个年龄组,然后外部查询按年龄组聚合。请注意,嵌套子查询不是必需的,也不会对性能有很大帮助,但用于避免在使用CASE时不得不重复丑陋的GROUP BY表达式。

然后使用以下PHP代码:

$sql2 = "...";  // use the above query
$result2 = $conn->query($sql2);
while ($row2 = $result2->fetch_assoc()) {
    $age_group = $row2['age_group']);
    $age_count = $row2['age_count']);
    echo $age_group.': '.$age_count;
}

答案 1 :(得分:3)

    SELECT CONCAT((FLOOR(`year`/5))*5,'-',((FLOOR(`year`/5))*5)+4) `range`,
    COUNT(*) qty 
    FROM persons  
    GROUP BY `range`

答案 2 :(得分:2)

试试这个:

$count_20_25 = 0;
$count_26_35 = 0;
$count_36_45 = 0;
$count_46_55 = 0;
$count_above_55 = 0;
$curr_year = date('Y');

$sql2 = "SELECT date_of_birth FROM persons";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
    $date_of_birth = explode('-', $row2['date_of_birth']);
    $year = $date_of_birth[0];
    $month = $date_of_birth[1];
    $day = $date_of_birth[2];
    $temp = abs($curr_year - $year);
    if($temp >= 20 && $temp <= 25)
    {
        $count_20_25++;
    }
    elseif($temp >= 25 && $temp <= 35)
    {
        $count_26_35++;
    }
    elseif($temp >= 36 && $temp <= 45)
    {
        $count_36_45++;
    }
    elseif($temp >= 46 && $temp <= 55)
    {
        $count_46_55++;
    }
    else
    {
        $count_above_55++;
    }
}

echo '20-25: '.$count_20_25.'<br>';
echo '26-35: '.$count_26_35.'<br>';
echo '36-45: '.$count_36_45.'<br>';
echo '46-55: '.$count_46_55.'<br>';
echo '55+: '.$count_above_55.'<br>';